/* ==========================================================================
 * Author: erman
 * Website: http://bagong.cn
 * Email: support@bagong.cn
 * ========================================================================== */

var BagongApp = function(){

    return {

        // =========================================================================
        // CONSTRUCTOR APP
        // =========================================================================
        init: function () {
            BagongApp.handleBase();
            BagongApp.handleSso();
        },

        // =========================================================================
        // SET UP BASE
        // =========================================================================
        handleBase: function () {
            $('#preloader .loader-wrapper').fadeOut('slow');
            $('#preloader').delay(350).fadeOut('slow');
            //点击数统计
            if($("#nearbyfind").is(":visible")){
                var loc = $("#nearbyfind").data("loc");
                $.getJSON(Init.url.base + "?m=Pet&a=LoadNearbyFind&callback=?",{ loc:loc },function(R){
                    if(R.result=="ok"){
                        $("#nearbyfind").html(R.data);
                    }
                });
            }

            $("a").bind('focus',function(){
                if(this.blur) {
                    this.blur();
                }
            });

            $('.make_qrcode').each(function(){
                var o = $(this), url= $(this).data("url");
                if(url!=""){
                    o.qrcode({width: 100,height: 100,text: url});
                }
            });

            //认领店铺
            $(".actionClaim").on("click",function(){
                $('.modal').modal("hide");
                if(Init.uid==0) {
                    $('#login-modal').modal();
                }else {
                    $('#ClaimBox').modal();
                }
                return false;
            });

            //提交认领申请
            $("form[name='saveClaim']").submit(function(){
                var o=$(this),param = o.serialize();
                $("#saveClaimBtn").addClass("disabled")
                $.getJSON(Init.url.base + '?m=User&o=index&a=saveClaim&callback=?',param,function(R){
                    if(R.result=="ok"){
                        $.alert("您的认领信息已经提交给我们，请耐心等待，我们将尽快审核");
                        $('#ClaimBox').modal('hide');
                        $(".actionClaim").parent().hide();
                    }else{
                        $.alert(R.message);
                    }
                    $("#saveClaimBtn").removeClass("disabled");
                });
                return false;
            });


            $("#baidumap").on("click", function () {
                jQuery.getScript("https://api.map.baidu.com/api?v=2.0&ak=uBrThqQXL2GSDtCIEaFvFLVh&callback=BaiduMapinitialize", function() {
                    $('#baidu-map-box').modal('show');
                });
            });
            $('#baidu-map-box').on('shown.bs.modal', function () {
                var o = $("#baidumap"), pp = o.data("loc"), title = o.data("title");
                $("#map_title").text(title);
                //载入百度地图
                if ($('#baidu_map').length > 0) {
                    if (pp.length > 0) {
                        pp = JSON.parse(pp);
                        var map = new BMap.Map("baidu_map");
                        map.centerAndZoom(new BMap.Point(pp[0], pp[1]), 13);
                        map.addControl(new BMap.NavigationControl());               // 添加平移缩放控件
                        map.addControl(new BMap.ScaleControl());                    // 添加比例尺控件
                        map.addControl(new BMap.OverviewMapControl());              //添加缩略地图控件
                        map.enableScrollWheelZoom();                            //启用滚轮放大缩小
                        map.addControl(new BMap.MapTypeControl());          //添加地图类型控件
                        var marker1 = new BMap.Marker(new BMap.Point(pp[0], pp[1]));  // 创建标注
                        map.addOverlay(marker1);
                        var link = 'https://api.map.baidu.com/marker?location=' + pp[1] + ',' + pp[0] + '&title=' + title + '&content=' + title + '&output=html';
                        var opts1 = {title: '<span style="font-size:14px;color:#0A8021">' + title + '</span>'};
                        var infoWindow1 = new BMap.InfoWindow("<div style='line-height:1.8em;font-size:16px;'><a href='" + link + "' target='_blank' >我要到这里去</a></div>", opts1);
                        marker1.openInfoWindow(infoWindow1);
                    }
                }
            });

            //分享模块
            $(".action_shop_share,.action_shop_share_index").on("click",function () {
                var url=Init.share_link,title=Init.share_title,content=Init.share_description;
                var html = '<div class="wxshare" style="width:100%; height:100%; position:fixed; z-index:100; left:0; left:0; background-color:rgba(0,0,0,0.7);display:none" onclick="$(this).hide()">\
                <img style="width:86%; position: absolute; right: 0" src = "'+Init.url.jic+'i/share/fenti.png">\
                </div>\
                <div class="share-s">\
                    <a href="javascript:void(0);" onclick="$(\'.wxshare\').show()"><img class="share-logo" src="'+Init.url.jic+'i/share/wei.png"></a>\
                    <a href="http://v.t.qq.com/share/share.php?url='+encodeURIComponent(url)+'&title='+content+'&summary=" target="_blank"><img class="share-logo" src="'+Init.url.jic+'i/share/ten.png"></a>\
                    <a href="http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url='+encodeURIComponent(url)+'&title='+title+'&summary='+content+'&desc='+content+'" target="_blank"><img class="share-logo" src="'+Init.url.jic+'i/share/qq-zone.png"></a>\
                    <a href="http://v.t.sina.com.cn/share/share.php?url='+encodeURIComponent(url)+'&title='+content+'&default_text=" target="_blank"><img class="share-logo" src="'+Init.url.jic+'i/share/sina.png"></a>\
                    <a href="http://widget.renren.com/dialotg/share?resourceUrl='+encodeURIComponent(url)+'&srcUrl='+encodeURIComponent(url)+'&title='+title+'&pic=&description='+content+'" target="_blank"><img class="share-logo" src="'+Init.url.jic+'i/share/ren.png"></a>\
                    <div class="clearfix"></div>\
                    <div class="share-cancel">取消</div>\
                </div>';
                $(".share-inner").html(html).show();
                $(".share-s").click(function (event) {
                    event.stopPropagation();
                });
                $(".share-cancel").click(function () {
                    $(".share-inner").hide();
                });
                $(".share-inner").click(function () {
                    $(".share-inner").hide();
                });
            });

            $(".share-cancel").click(function () {
                $(".share-inner").hide();
            });
            $(".share-inner").click(function () {
                $(".share-inner").hide();
            });

            $('.pop_over').popover();
            //提示自动加载
            $('[data-toggle="tooltip"]').tooltip();
            //图片延时加载
            $("img.lazy").lazyload();



            //微信二维码
            if($("#shop_weixin_qrcode_box").is(":visible")){
                $.getJSON(Init.url.base + "?m=shop&o=index&a=GetWeixinShopQrcode&callback=?", {id: Init.shop_id}, function (R) {
                    if (R.result == "ok") {
                        $(".shop_weixin_qrcode").attr("src", R.data);
                    }
                });
            }

            if (Init.is_weixin) {
                $.getJSON(Init.url.base + "?m=Info&o=index&a=AjaxBindWeixinInfo&callback=?", function (R) {
                });
            }

            //获取提醒信息数目
            if($('.message_count').is(":visible") || $('.notice_count').is(":visible")){
                $.getJSON(Init.url.base + "?m=Info&o=index&a=AjaxGetNoticeAlert&callback=?", {shop_id: Init.shop_id}, function (R) {
                    if (R.result == "ok") {
                        if (R.data.message_count > 0) {
                            $('.message_count').html(R.data.message_count).show();
                        }
                        if (R.data.notice_count > 0) {
                            $('.notice_count').html(R.data.notice_count).show();
                        }
                        if (R.data.message_count > 0) {
                            $(".user_notice").html(R.data.message_count).show();
                        } else {
                            $(".user_notice").html("").hide();
                        }
                    }
                });
            }
            //点击收藏
            $(".actionFav").on("click", function () {
                var o = $(this), id = o.data("id"), type = o.data("type");
                var action = o.children("i").hasClass("fa-heart-o") ? "AddFav" : "RemoveFav";
                if (action == "AddFav") {
                    $.getJSON(Init.url.base + '?m=User&a=' + action + '&callback=?', {id: id, type: type}, function (R) {
                        if (R.result == "ok") {
                            if (o.children("i").hasClass("fa-heart")) {
                                o.children("i").removeClass("fa-heart").addClass("fa-heart-o");
                            } else {
                                o.children("i").removeClass("fa-heart-o").addClass("fa-heart");
                            }
                        } else {
                            $.alert(R.message);
                        }
                    });
                }
                $("#follow-shop-box").modal("show");
                return false;
            });
            //显示卡余额

            if($("#my_account").length>0){
                var id = $("#my_account").data("id");
                $.getJSON(Init.url.base+"?m=shop&o=index&a=AjaxGetShopAccount&callback=?",{ shop_id:Init.shop_id,id:id },function(R){
                    if(R.result=="ok"){
                        $("#my_account").text(R.data.account);
                        $("#my_score").text(R.data.score);
                    }
                });
            }
            //举报
            $("form[name='saveJubaoPost']").submit(function () {
                var o = $(this), param = o.serialize();
                $.post(Init.url.base + 'index.php?m=Pet&a=AjaxJuBaoPost&callback=?', param, function (R) {
                    if (R.result == "ok") {
                        $.toast("举报成功！");
                        $('#jubaoBox').modal('hide');
                    } else {
                        $.alert(R.message);
                    }
                }, "json");
                return false;
            });
            //获取购物车数量
            if($(".cart_num").length>0){
                $.getJSON(Init.url.base+'?m=shop&o=index&a=GetCartNum&callback=?',{ shop_id:Init.shop_id },function(R){
                    if(R.result=="ok"){
                        if(R.data>0){
                            $(".cart_num").html(R.data).show();
                        }
                    }
                });
            }

            //获取订单数量
            if($(".order_num").length>0){
                $.getJSON(Init.url.base+'?m=shop&o=index&a=AjaxGetOrderAlert&callback=?',{ shop_id:Init.shop_id },function(R){
                    if(R.result=="ok"){
                        if(R.data>0){
                            $(".order_num").html(R.data).show();
                        }
                    }
                });
            }

        },

        // =========================================================================
        // 通行证
        // =========================================================================
        handleSso: function () {

            //登录 切换发送短信验证码登录
            $(".login_type").on("click", function () {
                var o = $(this), id = o.data("type");
                $(".login_type").removeClass("active");
                o.addClass("active");
                $(".input_login_type").hide();
                $("#" + id).show();
                $("." + id).show();//for login_bind
                if (id == "Phone_code") {
                    $("#PassportPassword").val("");
                    $(".sendLoginBindPhoneCode").show();
                    $(".sendLoginPhoneCode").show();
                } else {
                    $("#Phone_code").val("");
                    $(".sendLoginBindPhoneCode").hide();
                    $(".sendLoginPhoneCode").hide();
                }
            });

            //登录
            $("#PassportLoginForm").submit(function(){
                var submiturl = $(this).attr("action"),param = $(this).serialize();
                if($("#logname") == ""){
                    $.alert("用户名不能为空");
                    return false;
                }
                if($("#PassportPassword") == "" && $("#Phone_code") == ""){
                    $.alert("密码或者验证码不能为空");
                    return false;
                }
                $.post(submiturl+'&callback=?',param,function(R){
                    if(R.result=="ok"){
                        window.location.href=R.data.successUri;
                    }else{
                        $.alert(R.message);
                    }
                },"json");
                return false;
            });
            //注册
            $("#PassportRegForm").submit(function(){
                if($("#regPassword").val().length<6){
                    $.alert("密码长度不能小于6位");
                    return false;
                }

                var submiturl = $(this).attr("action"),param = $(this).serialize();
                var checkstatus = true;
                $(this).find('input:not(:submit)').each(function(){
                    var o = $(this);
                    if(o.val() == ""){
                        $.alert(o.attr("placeholder")+"不能为空");
                        checkstatus = false;
                        o.focus();
                    }
                });
                if(!checkstatus) return false;
                $("#register_submit").addClass("disabled").html("提交中...");
                $.post(submiturl+'&callback=?',param,function(R){
                    if(R.result=="ok"){
                        //window.location.reload()
                        var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                        window.location.href=window.location.href+ljf+"math="+10000*Math.random();
                    }else{
                        $.alert(R.message);
                        $("#register_submit").removeClass("disabled").html("申请注册");
                    }
                },"json");
                return false;
            });
            $('.sendLoginPhoneCode').on('click', function () {
                var o = $(this), phone = $.trim($("#logname").val());
                o.addClass("disabled").html("发送中");
                //发送短信
                $.getJSON('/?m=Passport&o=index&a=SendLoginPhoneCode&callback=?', {phone: phone}, function (R) {
                    if (R.result == "ok") {
                        $(".alert-warning").hide();
                        var time = 60;
                        o.html(function timeends() {
                            if (time < 0) {
                                time = 60;
                                o.removeClass("disabled").html("重新获取");
                                //$("#submitPhone_info").html('');
                            } else {
                                o.html("重新获取(" + time + ")");
                                //$("#submitPhone_info").html('已发送，1分钟后可重新获取');
                                time--;
                                setTimeout(timeends, 1000);
                            }
                        });
                    } else {
                        $.alert(R.message);
                        o.removeClass("disabled").html("发送验证码");
                    }
                });
                return false;
            });

            //如果是top手机注册
            if ($("#top-reg").length > 0 || $("#login-page").length > 0) {
                $("#code").val("");
                $('#actionSendMessage').on('click', function () {
                    var phone = $.trim($("#regname").val());
                    //$("#submitPhone_info").html('已发送，1分钟后可重新获取');
                    //发送短信
                    $.getJSON(Init.url.base + '?m=Passport&o=index&a=SendPhoneCode&callback=?', {phone: phone}, function (R) {
                        if (R.result == "ok") {
                            $(".alert-warning").hide();
                            var time = 60;
                            $('#actionSendMessage').html(function timeends() {
                                if (time < 0) {
                                    time = 60;
                                    $("#actionSendMessage").removeClass("disabled").html("重新获取");
                                    //$("#submitPhone_info").html('');
                                } else {
                                    $("#actionSendMessage").addClass("disabled").html("重新获取(" + time + ")");
                                    //$("#submitPhone_info").html('已发送，1分钟后可重新获取');
                                    time--;
                                    setTimeout(timeends, 1000);
                                }
                            });
                        } else {
                            $("#code").val("");
                            $(".alert-warning").show();
                            $("#telphone_info").html(R.message);
                        }
                    });
                    return false;
                });
                $("#regname").on("click", function () {
                    $(".alert-warning").hide();
                    $("#telphone_info").html("");
                });

                $("#agree").addClass("active");
            }

            //第三方登陆
            $('.app-login,.app-bind').on('click', function () {
                var o = $(this), type = o.data('type'), action = o.data('action');
                if (typeof (action) == 'undefined') {
                    action = type + "login";
                } else {
                    action = type + action;
                }
                var redirect = Init.successUri;
                $.getJSON(Init.url.base + "api/authlogin.php?action=" + action + "&callback=?", {redirect: redirect}, function(R) {
                    if (R.result == 'ok') {
                        window.location = R.data;
                    }
                })
            });
            //载入微信登录二维码
            $('#weichant-login-box').on('shown.bs.modal', function () {
                if($("#weichant_qrcode").html().length==0){
                    var obj = new WxLogin({
                        id:"weichant_qrcode",
                        appid: "wxb0326659c78f570a",
                        scope: "snsapi_login",
                        redirect_uri: Init.weixin_login_callback,
                        state: "",
                        style: "",
                        href: Init.url.jic+"c/wxlogin.css"
                    });
                }
            });

        },

        // =========================================================================
        // 用户中心
        // =========================================================================
        handleUserIndex: function () {



        },

        // =========================================================================
        // index
        // =========================================================================
        handleIndex: function () {
            if($(".swiper-container").length>0){
                var mySwiper = new Swiper('.swiper-container',{
                    pagination: '.swiper-pagination',
                    paginationClickable: true,
                    freeMode: false,
                    freeModeFluid: false,
                    loop:true,
                    grabCursor: true
                });
            }

            $("#album-zhankai").on("click",function(){
                $(this).hide();
                $("#album-more").slideDown();
                $("#album-shousuo").show();
            });

            $("#album-shousuo").on("click",function(){
                $(this).show();
                $("#album-more").slideUp()
                $("#album-zhankai").show();
                var scroll_offset = $(".shop-album").offset();
                $("body,html").animate({
                    scrollTop:scroll_offset.top
                },1000);
            });

            $(".actionJubaoModal").on("click",function(){
               $("#jubaoBox").modal("show");
            });





            /**
             * 保存消息
             */
            $("form[name='saveMessage']").submit(function(){
                var o=$(this),param = o.serialize(),sub = o.find('button[type="submit"]');
                sub.addClass("disabled").html("发送中...");
                $.getJSON(Init.url.base + '?m=Message&a=SaveMessage&callback=?',param,function(R){
                    if(R.result=="ok"){
                        $('#messageBox').modal('hide');
                        $("textarea[name='message']").val("");
                        $("input[name='message']").val("");
                    }else{
                        $.alert(R.message);
                    }
                    sub.removeClass("disabled").html("发送");
                });
                return false;
            });

            //获取首页商品
            if($("#index_goods_box").is(":visible")){
                $.getJSON(Init.url.base + "?m=shop&o=index&a=GetShopGoods&callback=?",{ sid:Init.shop_id },function(R){
                    if(R.result=="ok"){
                        $("#index_goods_box").html(R.data);
                    }else{
                        $("#index_goods_box").parent().hide();
                    }
                });
            }
            //load brandshops
            if($("#myothershops").is(":visible")){
                var brand_id = $("#myothershops").data("brandid");
                $.getJSON(Init.url.base + "?m=shop&o=index&a=LoadMyOtherShop&callback=?",{ page:"index",sid:Init.shop_id,uid:Init.uid,brand_id:brand_id },function(R){
                    if(R.result=="ok"){
                        $("#myothershops").html(R.data);
                    }
                });
            }
            //load nearbyShop
            if($("#nearbyShop").is(":visible")){
                var loc = $("#nearbyShop").data("loc");
                var type = $("#nearbyShop").data("type");
                $.getJSON(Init.url.base + "?m=shop&o=index&a=LoadNearbyShop&callback=?",{ loc:loc,page:"index",type:type },function(R){
                    if(R.result=="ok"){
                        $("#nearbyShop").html(R.data);
                    }
                });
            }

            if($("#recommendShop").is(":visible")){
                $.getJSON(Init.url.base + "?m=shop&o=index&a=LoadRecommendShop&callback=?",{ page:"index",sid:Init.shop_id},function(R){
                    if(R.result=="ok"){
                        $("#recommendShop").html(R.data);
                    }
                });
            }
        },

        // =========================================================================
        // BACK TOP
        // =========================================================================

        handleGoodsList: function () {
            var menuwidth  = document.body.clientWidth/2; // 边栏宽度
            var menuspeed  = 400; // 边栏滑出耗费时间

            var $bdy       = $('body');
            var $container = $('#navi-container');
            var $burger    = $('#hamburgermenu');
            var negwidth   = "-"+menuwidth+"px";
            var poswidth   = menuwidth+"px";


            if($("#category_list").length>0){
                $('#category_list li:eq(0) a').tab('show');
            }

            $('.menubtn').on('click',function(e){
                if($bdy.hasClass('openmenu')) {
                    jsAnimateMenu('close');
                } else {
                    jsAnimateMenu('open');
                }
            });

            $('.overlay').on('click', function(e){
                if($bdy.hasClass('openmenu')) {
                    jsAnimateMenu('close');
                }
            });

            function jsAnimateMenu(tog) {
                if(tog == 'open') {
                    $bdy.addClass('openmenu');

                    $container.animate({marginRight: negwidth, marginLeft: poswidth}, menuspeed);
                    $burger.animate({width: poswidth}, menuspeed);
                    $('.overlay').animate({left: poswidth}, menuspeed);
                }

                if(tog == 'close') {
                    $bdy.removeClass('openmenu');

                    $container.animate({marginRight: "0", marginLeft: "0"}, menuspeed);
                    $burger.animate({width: "0"}, menuspeed);
                    $('.overlay').animate({left: "0"}, menuspeed);
                }
            }

            $("img.lazy").lazyload({
                event : "sporty"
            });

            $('#category_list a').click(function (e) {
                $(this).tab('show');
                var id = $(this).attr("href");
                console.log(id);
                $(window).trigger('scroll');
            });


            $(".form-search-goods").pin({
                containerSelector: ".container"
            });

            $('.searchGoods').popover();

            $(".view_tab ").on("click",function(){
                $(".view_tab").removeClass("active");
                $(this).addClass("active");
            });

            $(".view_tab").on("click",function(){
                var type = $(this).data("type");
                $.getJSON(Init.url.base+'?m=shop&o=index&a=AjaxSetMyProductViewType&callback=?',{ sid:Init.shop_id,type:type },function(R){
                });
            });


/*            if($("#hamburgermenu").length>0){
                $.getJSON(Init.url.base+'?m=shop&o=index&a=AjaxLoadShopCategory&callback=?',{ sid:Init.shop_id },function(R){
                    if(R.result=="ok"){
                        $("#hamburgermenu").html(R.data);
                    }
                });
            }*/




            $(".wm-close-button").on("click",function(){
                $(".m-popup-wrapper").hide();
                $(".wd_p_cart").show();
                BagongApp.handleHideOverlay();
            });
            $(".actionAddListCart").on("click",function(){
                var addcart_o = $(this),id = addcart_o.data("id");
                $.getJSON(Init.url.base+'?m=shop&o=index&a=AjaxGetgoods&callback=?',{ id:id },function(R){
                    if(R.result=="ok"){
                        $("#cart_box").html(R.data).show();
                        BagongApp.handleShowOverlay();
                        $(".m-popup-wrapper").show();


                        $(".wm-close-button").on("click",function(){
                            $(".m-popup-wrapper").hide();
                            $(".wd_p_cart").show();
                            BagongApp.handleHideOverlay();
                            $(".m-popup-wrapper").remove();
                        });

                        var select = false;
                        $(".wm-gd-skuItem-group").find(".actionChangeGuige").each(function(){
                            if($(this).hasClass("btn-danger")){
                                select = true;
                            }
                        });
                        if(!select){
                            var o = $(".wm-gd-skuItem-group").find(".actionChangeGuige").not("disabled");
                            var json = o.data("json");
                            BagongApp.handleGoodsDetailSelectGuige(json);
                        }
                        BagongApp.handleGoodsDetailCountPrice();
                        //保存规格
                        $(".actionChangeGuige").unbind("click").click(function(){
                            var o = $(this);
                            $(".actionChangeGuige").removeClass("btn-danger").addClass("btn-default");
                            o.removeClass("btn-default").addClass("btn-danger");
                            var json = o.data("json");
                            BagongApp.handleGoodsDetailSelectGuige(json);
                            BagongApp.handleGoodsDetailCountPrice();
                        });

                        $('.btn-number').click(function(e){
                            e.preventDefault();
                            var fieldName = $(this).attr('data-field');
                            var type      = $(this).attr('data-type');
                            var input = $(this).parent().parent().children("."+fieldName);
                            var currentVal = parseInt(input.val());
                            if (!isNaN(currentVal)) {
                                if(type == 'minus') {
                                    if(currentVal > input.attr('min')) {
                                        input.val(currentVal - 1).change();
                                    }

                                } else if(type == 'plus') {

                                    if(currentVal < input.attr('max')) {
                                        input.val(currentVal + 1).change();
                                    }

                                }
                                BagongApp.handleGoodsDetailCountPrice();
                            } else {
                                input.val(0);
                            }
                        });
                        $('.input-number').focusin(function(){
                            $(this).data('oldValue', $(this).val());
                        });
                        $('.input-number').change(function() {
                            var minValue =  parseInt($(this).attr('min'));
                            var maxValue =  parseInt($(this).attr('max'));
                            var valueCurrent = parseInt($(this).val());

                            var name = $(this).attr('name');
                            if(valueCurrent >= minValue) {
                                $(".btn-number[data-type='minus'][data-field='"+name+"']").removeAttr('disabled');
                            } else {
                                //alert('Sorry, the minimum value was reached');
                                $(this).val($(this).data('oldValue'));
                            }
                            if(valueCurrent <= maxValue) {
                                $(".btn-number[data-type='plus'][data-field='"+name+"']").removeAttr('disabled');
                            } else {
                                //alert('Sorry, the maximum value was reached');
                                $(this).val($(this).data('oldValue'));
                            }
                        });
                        $(".input-number").keydown(function (e) {
                            // Allow: backspace, delete, tab, escape, enter and .
                            if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
                                    // Allow: Ctrl+A
                                (e.keyCode == 65 && e.ctrlKey === true) ||
                                    // Allow: home, end, left, right
                                (e.keyCode >= 35 && e.keyCode <= 39)) {
                                // let it happen, don't do anything
                                return;
                            }
                            // Ensure that it is a number and stop the keypress
                            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                                e.preventDefault();
                            }
                        });

                        //加入购物车
                        $('.actionAddCart').on('click', function() {
                            BagongApp.saveCart(addcart_o);
                            return false;
                        });


                    }
                });
            });

        },


        // =========================================================================
        //
        // =========================================================================

        saveCart:function(addcart_o){
            var json = BagongApp.selectSkuInfo;
            if(!json.id){
                alert("没选规格");
                return false;
            }
            var param = {};
            var order_num = $("#product_order_num").val();
            param.quantity = order_num;
            param.shop_id = Init.shop_id;
            param.token = $("#is_token").val();
            param.product_id = json.goods_id;
            param.product_sku_id = json.id;
            param.product_name = $("#product_name").val();
            param.pic = $("#goods_selected_pic").val();
            param.quantity = order_num;
            param.product_type = $("#product_type").val();
            param.product_user_price = json.price;
            param.product_price = json.origin_price;
            param.product_guige = json.name+":"+json.value;
            param.is_pet = json.pet_type?1:0;
            if($("#buyer_shop_id").length>0){
                param.buyer_shop_id = $("#buyer_shop_id").val();
            }
            console.log(param);
            $.showLoading("加载中...");
            $.ajax({
                url: "https://xcx.api.kadian.cn/order/savecart",
                type:'post',
                dataType:"jsonp",
                data: param,
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                success: function (R) {
                    if(R.result=="ok"){
                        if($(".cart_num").text()!=""){
                            $(".cart_num").text(parseInt($(".cart_num").text())+parseInt(order_num)).show();
                        }else{
                            $(".cart_num").text(parseInt(order_num)).show();
                        }
                        if(addcart_o){
                            addcart_o.html("<i class='fa fa-check'></i>").unbind("click");
                        }
                    }else{
                        $.alert(R.message);
                    }
                },
                complete:function(){
                    $(".m-popup-wrapper").hide();
                    $(".wd_p_cart").show();
                    BagongApp.handleHideOverlay();
                    $(".m-popup-wrapper").remove();
                    $.hideLoading();

                }
            })
            return false;
        },
        handleGoodsDetailSelectGuige: function (json) {
            if(typeof(json)=="string"){
                json = JSON.parse(json);
            }
            console.log("handleGoodsDetailSelectGuige json",json);
            if(json.hasOwnProperty("quantity")){
                console.log("handleGoodsDetailSelectGuige json.quantity",json.quantity);
                $("#product_order_num").attr("max",json.quantity);
                if(parseFloat($("#product_order_num").val())>json.quantity && json.quantity>0){
                    $("#product_order_num").val(json.quantity);
                }
                if(json.quantity>0){
                    $("#product_order_num_box").show();
                    $("#product_order_num_empty").hide();
                }else{
                    $("#product_order_num").val(0);
                    $("#product_order_num_box").hide();
                    $("#product_order_num_empty").show();
                }
            }
            var classname = "guige_"+json.id;
            $("."+classname).each(function(){
                $(this).removeClass("btn-default").addClass("btn-danger");
            });
            var goods_title = $("#goods_title").text();
            var user_discount = parseFloat($("#user_discount").val());
            var user_price_level = $("#user_price_level").val();
            if(typeof(json.discount) == "undefined" || json.discount==0){
                json.discount = 10;
            }
            json.origin_price = parseFloat(json.origin_price);
            var order_name_extra = "_"+(typeof(json.discount_desc)!="undefined"?json.discount_desc:"会员价"),
            price_pre = (typeof(json.discount_desc)!="undefined"?json.discount_desc:"会员价")+"：",
            goods_price = json.price;

            $(".goods_account").text(json.origin_price.toFixed(2));
            $("#product_price").val(json.origin_price);
            $("#product_user_price").val(goods_price);

            if(goods_price!=json.origin_price){
                $(".goods_account").addClass("del");
                $(".goods_account_user").text(price_pre+(goods_price.toFixed(2)));
            }else{
                $(".goods_account").removeClass("del");
                $(".goods_account_user").text("");
            }

            if(typeof(json.id) != "undefined"){
                $("#product_sku_id").val(json.id);
            }
            $("#product_guige").val(json.name+ "："+ json.value );
            $("#product_name").val(goods_title+order_name_extra);

            if(typeof(json.quantity) == "undefined" || parseInt(json.quantity)<=0){
                $(".addCart").find("button").addClass("disabled");
            }else{
                $(".addCart").find("button").removeClass("disabled");
            }
            BagongApp.selectSkuInfo = json;

        },
        handleGoodsDetailCountPrice: function () {
            if($("#product_price").length>0){
                var order_num = parseInt($("#product_order_num").val());
                var price = parseFloat($("#product_user_price").val().replace(/,/g,""));
                $(".danjia").text(price.toFixed(2));
                var kd_price = parseFloat($("#cart_kd_price").text());
                var account =  parseFloat(order_num)*parseFloat(price)+kd_price;
                $("#account").text(account.toFixed(2));
                $("input[name='account']").val(account.toFixed(2));
            }
        },
        handleGoodsDetail: function () {
            if($(".swiper-container").length>0){
                var mySwiper = new Swiper('.swiper-container',{
                    pagination: '.swiper-pagination',
                    paginationClickable: true,
                    freeMode: false,
                    freeModeFluid: false,
                    loop:true,
                    grabCursor: true
                });
            }
            var select = false;
            $(".wd_p_head").find(".actionChangeGuige").each(function(){
                if($(this).hasClass("btn-danger") && !$(this).hasClass("disabled")){
                    select = true;
                    let json = $(this).data("json");
                    if(json){
                        BagongApp.handleGoodsDetailSelectGuige(json);
                    }
                }
            });
            if(!select){
                var o = $(".wd_p_head").find(".actionChangeGuige:first");
                var json = o.data("json");
                BagongApp.handleGoodsDetailSelectGuige(json);
            }
            $("img.lazy").lazyload();
            //计算价格
            BagongApp.handleGoodsDetailCountPrice();
            $("#addcart").on("click",function(){
                BagongApp.handleShowOverlay();
                $(".m-popup-wrapper").show();
                $(".wd_p_cart").hide();
                $(".actionAddCart").show();
                $("#cart_kd_price").html(0).parent().hide();
                $(".buyNow").hide();
                BagongApp.handleGoodsDetailCountPrice();
            });
            $("#buynow").on("click",function(){
                BagongApp.handleShowOverlay();
                $(".m-popup-wrapper").show();
                $(".wd_p_cart").hide();
                $(".actionAddCart").hide();
                var kd_price = $("input[name='kuaidifee']").val();
                $("#cart_kd_price").html(kd_price).parent().show();
                $(".buyNow").show();
                BagongApp.handleGoodsDetailCountPrice();
            });
            $(".wm-close-button").on("click",function(){
                $(".m-popup-wrapper").hide();
                $(".wd_p_cart").show();
                BagongApp.handleHideOverlay();
            });



            if($('#star').length>0){
                $('#star').raty({
                    space: false,
                    hints: ['很差', '不好', '一般', '好', '非常好'],
                    target    : '#hint',
                    width: 100,
                    path: Init.url.jic+'i/',
                    score: 5,
                    targetText: ''
                });
            }


            //保存商品评论
            $("form[name='saveProductComment']").submit(function(){
                var o=$(this),param = o.serialize();
                $.post(Init.url.base+'?m=User&o=index&a=SaveProductComment&callback=?',param,function(R){
                    if(R.result=="ok"){
                        $('#content').val('');
                    }else{
                        $.alert(R.message);
                    }
                },"json");
                return false;
            });

            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                //获得评论
                if($("#tab-comment").is(":visible")){
                    var id = $("#tab-comment").data("id");
                    $.getJSON(Init.url.base+'?m=merchant&o=index&a=AjaxGetProductComment&callback=?',{ shop_id:Init.shop_id,id:id },function(R){
                        if(R.result=="ok"){
                            $("#comment-list").html(R.data).show();
                        }
                    })
                }
            });

            //加入购物车
            $('.actionAddCart').on('click', function() {
                BagongApp.saveCart(null);
                return false;
            });

            //保存规格
            $(".actionChangeGuige").on("click",function(){
                var o = $(this);
                $(".actionChangeGuige").removeClass("btn-danger").addClass("btn-default");
                o.removeClass("btn-default").addClass("btn-danger");
                var json = o.data("json");

                BagongApp.handleGoodsDetailSelectGuige(json);
                BagongApp.handleGoodsDetailCountPrice();
            });

            function saveOrderSubmit(submit_class){
                var json = BagongApp.selectSkuInfo;
                var BuyNowInfo = {};
                var order_num = parseFloat($("#product_order_num").val());
                BuyNowInfo.buy_from = "h5";
                BuyNowInfo.type = "shop_product";
                var apply_data = {};
                apply_data.sku = json;
                apply_data.active = true;
                apply_data.product_id = json.goods_id;
                apply_data.product_type = $("#product_type").val();
                apply_data.product_sku_id  = json.id;
                apply_data.product_price  = json.origin_price;
                apply_data.product_user_price  = json.price;
                apply_data.product_name = $("#product_name").val();
                apply_data.product_guige = json.name+":"+json.value;
                apply_data.product_order_num = order_num;
                BuyNowInfo.goods_list = [];
                BuyNowInfo.goods_list.push(apply_data);
                BuyNowInfo.account = json.price*order_num;
                BuyNowInfo["shop_id"] = Init.shop_id;
                BuyNowInfo["token"] = $("#is_token").val();
                BuyNowInfo["verifyOrder"] = $("#verify_Order").length>0?$("#verify_Order").val():0;
                if($("#buyer_shop_id").length>0){
                    BuyNowInfo.buyer_shop_id = parseInt($("#buyer_shop_id").val());
                }
                $.showLoading("正在加载...");
                var text =  $("."+submit_class).html();
                $("."+submit_class).addClass("disabled").html("提交中");
                $.ajax({
                    url: "https://xcx.api.kadian.cn/order/saveorder",
                    type:'post',
                    dataType:"jsonp",
                    data: BuyNowInfo,
                    xhrFields: {
                        withCredentials: true
                    },
                    crossDomain: true,
                    success: function (R) {
                        if(R.result=="ok"){
                            window.location.href= R.data.redirect;
                        }else{
                            $.alert(R.message);
                            if(R.message=="完善联系方式"){
                                $("#wanshan_ziliao").modal("show");
                                return false;
                            }
                            $("."+submit_class).removeClass("disabled").html(text);
                        }
                    },
                    complete:function(){
                        $.hideLoading();
                    }
                })
            }

            function orderSubmit(submit_class){
                var param = $("form[name='saveOrder']").serialize();
                $.showLoading("正在加载...");
                var quick = submit_class=="actionQuickBuy"?"&quick=1":"";
                var text =  $("."+submit_class).html();
                $("."+submit_class).addClass("disabled").html("提交中");
                setTimeout(function(){
                    $("."+submit_class).removeClass("disabled").html(text);
                },5000);
                $.post(Init.url.base+'?m=Shop&o=index&a=saveOrder'+quick+'&buy_from='+submit_class+'&callback=?',param,function(R){
                    if(R.result=="ok"){
                        window.location.href= R.data.redirect;
                    }else{
                        $.hideLoading();
                        if(R.message=="完善联系方式"){
                            $("#wanshan_ziliao").modal("show");
                            return false;
                        }
                        $.alert(R.message);
                        $("."+submit_class).removeClass("disabled").html(text);
                    }
                },"json");
            }
            //闪电购买  停用了 220804
            $('.actionQuickBuy').on('click', function() {
                orderSubmit("actionQuickBuy");
                return false;
            });
            //立即购买
            $('.actionBuyNow').on('click', function() {
                //orderSubmit("actionBuyNow");
                saveOrderSubmit("actionBuyNow");
                return false;
            });

            $("#wanshan_submit").on("click",function(){
                if($("#wanshan_contact_tel").val().length<=0){
                    $("#wanshan_contact_tel").focus();
                }
                var phone = $("#wanshan_contact_tel").val();
                var patrn = /^\d{3}[-| ]?\d{8}[-| ]?\d?$/;
                if (!patrn.exec(phone)) {

                    $.alert("手机号格式不正确");
                    $("#wanshan_contact_tel").focus();
                    return false;
                }
                $("input[name='contact_tel']").val(phone);
                $("#wanshan_ziliao").modal("hide");
                $('#wanshan_ziliao').on('hidden.bs.modal', function (e) {
                    orderSubmit("actionQuickBuy");
                })
            });



            //点击收藏
            $(".actionProductFav").on("click",function(){
                var o = $(this),id = o.data("id"),type= o.data("type");
                var action = o.children("i").hasClass("fa-heart-o")?"AddFav":"RemoveFav";
                $.getJSON(Init.url.base+'?m=User&a='+action+'&callback=?',{ id:id,type:type },function(R){
                    if(o.children("i").hasClass("fa-heart")){
                        o.children("i").removeClass("fa-heart").addClass("fa-heart-o");
                    }else{
                        o.children("i").removeClass("fa-heart-o").addClass("fa-heart");
                    }
                });
                return false;
            });

            $('.btn-number').click(function(e){
                e.preventDefault();
                var fieldName = $(this).attr('data-field');
                var type      = $(this).attr('data-type');
                var input = $(this).parent().parent().children("."+fieldName);
                //var input = $("input[name='"+fieldName+"']");
                var currentVal = parseInt(input.val());
                if (!isNaN(currentVal)) {
                    if(type == 'minus') {
                        if(currentVal > input.attr('min')) {
                            input.val(currentVal - 1).change();
                        }

                    } else if(type == 'plus') {

                        if(currentVal < input.attr('max')) {
                            input.val(currentVal + 1).change();
                        }

                    }
                    BagongApp.handleGoodsDetailCountPrice();
                } else {
                    input.val(0);
                }
            });
            $('.input-number').focusin(function(){
                $(this).data('oldValue', $(this).val());
            });
            $('.input-number').change(function() {
                var minValue =  parseInt($(this).attr('min'));
                var maxValue =  parseInt($(this).attr('max'));
                var valueCurrent = parseInt($(this).val());

                var name = $(this).attr('name');
                if(valueCurrent >= minValue) {
                    $(".btn-number[data-type='minus'][data-field='"+name+"']").removeAttr('disabled');
                } else {
                    //alert('Sorry, the minimum value was reached');
                    $(this).val($(this).data('oldValue'));
                }
                if(valueCurrent <= maxValue) {
                    $(".btn-number[data-type='plus'][data-field='"+name+"']").removeAttr('disabled');
                } else {
                    //alert('Sorry, the maximum value was reached');
                    $(this).val($(this).data('oldValue'));
                }
            });
            $(".input-number").keydown(function (e) {
                // Allow: backspace, delete, tab, escape, enter and .
                if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
                        // Allow: Ctrl+A
                    (e.keyCode == 65 && e.ctrlKey === true) ||
                        // Allow: home, end, left, right
                    (e.keyCode >= 35 && e.keyCode <= 39)) {
                    // let it happen, don't do anything
                    return;
                }
                // Ensure that it is a number and stop the keypress
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
            });

            //loadcoupon
            if($("#coupon_box").length>0){
                var id = $("#coupon_box").data("id");
                $.getJSON(Init.url.base+"?m=Shop&o=index&a=LoadCoupons&callback=?",{ type:"goods",id:id,sid:Init.shop_id },function(R){
                    if(R.result=="ok"){
                        $("#coupon_box").html(R.data);
                    }
                });
            }
        },
        handleShowOverlay: function () {
            $("#body_overlay").height(document.body.scrollHeight).width(document.body.scrollWidth).show();
            // fadeTo第一个参数为速度，第二个为透明度
            // 多重方式控制透明度，保证兼容性，但也带来修改麻烦的问题
        },
        handleHideOverlay: function () {
            $("#body_overlay").fadeOut(200);
        },


        handleCreateUpload:function(button_id,button_html){
            var uploader = new qq.FineUploader({
                element: document.getElementById(button_id),
                request: {
                    endpoint: Init.url.base+'?m=Upload&a=Upload',
                    inputName:"upfile"
                },
                text: {
                    uploadButton: button_html
                },
                callbacks: {
                    onUpload:  function(id,  fileName)  {
                        $("#loading").html(" <img src='"+Init.url.jic+"i/loading_s.gif'> &nbsp;别着急，我正在努力的帮你把"+fileName+"图片往服务器上搬呐....").show();
                    },
                    onComplete:  function(id,  fileName,  responseJSON)  {
                        if( typeof(responseJSON)=="undefined"){
                            $.alert("上传失败，请重新上传");
                            return false;
                        }
                        $("#loading").hide();
                        var domainpre = 'http://bagong.oss-cn-qingdao.aliyuncs.com/';
                        var sLi="";
                        sLi+='<li class="clearfix">';
                        sLi+='<a class="pb-photo-li-move" title="拖动调整图片顺序">移动</a>';
                        sLi+='<a class="pb-photo-li-rm">删除</a>';
                        sLi+='<span class="pb-photo-li-thumb"><img src="'+domainpre+responseJSON.src+'"  data-src="'+domainpre+responseJSON.src+'"  data-width="'+responseJSON.width+'" data-height="'+responseJSON.height+'" data-type="'+responseJSON.type+'"></span>';
                        sLi+='<textarea class="pb-photo-desc" placeholder="输入对该图片的简单描述"></textarea>';
                        sLi+="</li>";
                        $('#pb-photo-list').prepend(sLi);
                        $("#savePetPic").removeClass("disabled");
                        BagongApp.handleAfterUpload();
                    }
                },
                debug: true
            });
        },
        handleCreateAvatarUpload:function(button_id,button_html){
            var uploader = new qq.FineUploader({
                element: document.getElementById(button_id),
                request: {
                    endpoint: Init.url.base+'?m=Upload&o=index&a=Upload',
                    inputName:"upfile"
                },
                text: {
                    uploadButton: button_html
                },
                validation:{
                    allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
                    sizeLimit: 2004800 // 200 kB = 200 * 1024 bytes
                },
                callbacks: {
                    onUpload:  function(id,  fileName)  {
                        $("#avatar").attr("src",Init.url.jic+"i/loading_m.gif");
                        $("#pet_avatar").attr("src",Init.url.jic+"i/loading_m.gif");
                    },
                    onComplete:  function(id,  fileName,  R)  {
                        if(R.result=="ok"){
                            $("#avatar").attr("src","http://bagong.oss-cn-qingdao.aliyuncs.com/"+R.src);
                            $("#pet_avatar").attr("src","http://bagong.oss-cn-qingdao.aliyuncs.com/"+R.src);
                            $("input[name='avatar']").val(R.src);
                            $("input[name='pet_avatar']").val(R.src);
                        }else{
                            BagongApp.handleAfterUpload();
                        }

                    }
                },
                debug: true
            });
        },
        handleAfterUpload:function(){
            $('.pb-photo-li-rm').on('click',function(){
                $(this).parent().remove();
                return false;
            });
            //拖动动作
            if($("#pb-photo-list").length>0){
                var sort_id = document.getElementById('pb-photo-list');
                Sortable.create(sort_id, {
                    animation: 150,
                    draggable: '.clearfix'
                });
            }
        },
        handleSetTixing:function(){
            //绑定手机号之：发送短信验证码
            $("#actionSendPhoneMessage").on("click",function(){
                var o = $(this),phone = $("#u-phone").val();
                o.addClass("disabled").html("发送中");
                //发送短信
                $.post(Init.url.base+'?m=Passport&o=index&a=SendPhoneCode&callback=?',{ phone:phone,type:"remind_bind" },function(R){
                    if(R.result=="ok"){
                        $("#phone-notice-msg").hide();
                        var time=120;
                        o.html(function timeends(){
                            if( time < 0){
                                time=60;
                                o.removeClass("disabled").html("重新获取");
                            }else{
                                o.addClass("disabled").html("重新获取("+time+")");
                                time--;
                                setTimeout(timeends,1000);
                            }
                        });
                        $("#verifyCodeBox").show();
                        $("#phone-code").val("");
                    }else{
                        $("#phone-code").val("");
                        $("#phone-notice-msg").show().html(R.message);
                    }
                },"json");
                return false;
            });

            //绑定手机号之：验证手机号
            $("form[name='bindRemindPhone']").submit(function(){
                var phone = $("#u-phone").val();
                var param = $(this).serialize();
                $.post(Init.url.base+'?m=User&a=BindRemindPhone&callback=?',param,function(R){
                    if(R.result=="ok"){
                        $("#bind-phone-box").hide();
                        $(".log_mobile").text(phone).show();
                        $("#phone-notice-msg").hide();
                    }else{
                        $("#phone-code").val("");
                        $("#phone-notice-msg").show().html(R.message);
                    }
                },"json")
                return false;
            });

            $("#actionChangePhone").on("click",function(){
                $("#bind-phone-box").show();
                $("#phone-notice-msg").hide();
                $(".log_mobile").hide();
            });

            //修改邮箱
            $("#changeEmail").click(function(){
                $("#email-box").hide();
                $("#changeemail-box").show();
            });
            $("#close-changeemaill-box").click(function(){
                $("#changeemail-box").hide();
                $("#email-box").show();
            });

            $(".actionSendEmailCode").on("click",function(){
                var email = $("input[name='email']").val();
                var o = $(this);
                o.addClass("disabled").html("发送中");
                $.getJSON(Init.url.base+'?m=passport&o=index&a=SendEmailCode&callback=?',{email:email},function(R){
                    if(R.result=="ok"){
                        $("#verifyMailCodeBox").show();
                        o.removeClass("disabled").html("再次发送");
                    }else{
                        $.alert(R.message);
                    }
                });
                o.removeClass("disabled").html("再次发送");
            });

            //绑定提醒邮件
            $("form[name=bindRemindEmail]").submit(function(){
                var param = $(this).serialize();
                //发送激活邮件
                $.post(Init.url.base+'?m=user&o=index&a=bindRemindEmail&callback=?',param,function(R){
                    if(R.result=="ok"){
                        var email = $("input[name='email']").val();
                        $("#remind_email").text(email);
                        $("input[name='email_code']").val("");
                        $("#email-box").show();
                        $("#verifyMailCodeBox").hide();
                        $("#changeemail-box").hide();
                        $.toast("保存成功！");
                    }else{
                        $.alert(R.message);
                    }
                },"json");
                return false
            });

            //修改手机号
            $("#changeMobile").click(function(){
                $("#mobile-box").hide();
                $("#changemobile-box").show();
                $("#verifyMobile").click(function(){
                    var email = $(this).prev();
                    if(email.val().length<1){
                        email.focus();
                        return false;
                    }else{
                        $("#changemobile-box").hide();
                        $("#mobile-box").show();
                        $("#log_mobile").text(email.val());
                    }
                });
                $("#close-changemobile-box").click(function(){
                    $("#changemobile-box").hide();
                    $("#mobile-box").show();
                })
            })
        },
        handleEditUser:function(){
            if($("#tdumbnail-fine-uploader").length>0){
                BagongApp.handleCreateAvatarUpload("tdumbnail-fine-uploader","上传头像");
            }
            //绑定手机号之：发送短信验证码
            $("#actionSendPhoneMessage").on("click",function(){
                //var phone = $("input[name='phone']").val();
                var phone = $("#u-phone").val();
                //发送短信
                $.post(Init.url.base+'?m=Passport&o=index&a=SendPhoneCode&callback=?',{ phone:phone,type:"bind" },function(R){
                    if(R.result=="ok"){
                        $("#phone-notice-msg").hide();
                        var time=60;
                        $('#actionSendPhoneMessage').html(function timeends(){
                            if( time < 0){
                                time=60;
                                $("#actionSendPhoneMessage").removeClass("disabled").html("重新获取");
                            }else{
                                $("#actionSendPhoneMessage").addClass("disabled").html("重新获取("+time+")");
                                time--;
                                setTimeout(timeends,1000);
                            }
                        });
                        $("#verifyCodeBox").show();
                        $("#phone-code").val("");
                    }else{
                        $("#phone-code").val("");
                        $("#phone-notice-msg").show().html(R.message);
                    }
                },"json");
                return false;
            });

            //绑定手机号之：绑定手机号为登录帐号
            $("#actionBindPhone").on("click",function(){
                var phone = $("#u-phone").val(),code = $("#phone-code").val();
                $.post(Init.url.base+'?m=User&a=BindPhone&callback=?',{ phone:phone,code:code,type:"bind" },function(R){
                    if(R.result=="ok"){
                        $("#bind-phone-box").hide();
                        $(".log_mobile").text(phone).show();
                        $("#phone-notice-msg").hide();
                    }else{
                        $("#phone-code").val("");
                        $("#phone-notice-msg").show().html(R.message);
                    }
                },"json");
                return false;
            });

            $("#actionChangePhone").on("click",function(){
                $("#bind-phone-box").show();
                $("#phone-notice-msg").hide();
                $(".log_mobile").hide();
            });

            //修改邮箱
            $("#changeEmail").click(function(){
                $("#email-box").hide();
                $("#changeemail-box").show();
                $(".verifyEmail").click(function(){
                    var email = $(this).prev();
                    if(email.val().length<1){
                        email.focus();
                        return false;
                    }else{
                        $("#changeemail-box").hide();
                        $("#email-box").show();
                        $("#log_email").text(email.val());
                    }
                });
                $("#close-changeemaill-box").click(function(){
                    $("#changeemail-box").hide();
                    $("#email-box").show();
                })
            });
            //发送绑定邮件
            $(".sendEmail").on("click",function(){
                var o = $(this),input=o.prev(),email = o.prev().val();
                if(email.length<1){
                    input.focus();
                    return false;
                }else{
                    //发送激活邮件
                    $.post(Init.url.base+'?m=user&o=index&a=SendBindEmail&callback=?',{ email:email },function(R){
                        if(R.result=="ok"){
                            o.removeClass("sendEmail").text("激活邮件已发送，请去邮箱查收");
                        }else{
                            $.alert(R.message);
                        }
                    },"json");
                    return false
                }
            });

            //修改手机号
            $("#changeMobile").click(function(){
                $("#mobile-box").hide();
                $("#changemobile-box").show();
                $("#verifyMobile").click(function(){
                    var email = $(this).prev();
                    if(email.val().length<1){
                        email.focus();
                        return false;
                    }else{
                        $("#changemobile-box").hide();
                        $("#mobile-box").show();
                        $("#log_mobile").text(email.val());
                    }
                });
                $("#close-changemobile-box").click(function(){
                    $("#changemobile-box").hide();
                    $("#mobile-box").show();
                })
            });

            //保存个人资料
            $("form[name='updateUserInfo']").submit(function(){
                var pagram = $(this).serialize();
                $.post(Init.url.base+'?m=user&o=index&a=UpdateUserinfo&callback=?',pagram,function(R){
                    if(R.result=="ok"){
                        $.toast("修改成功");
                        var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                        window.location.href=window.location.href+ljf+"math="+10000*Math.random();

                    }else{

                        $.alert(R.message);
                    }
                },"json");
                return false;
            });
            //修改密码
            $("form[name='editpwsform']").submit(function(){
                var pagram = $("form[name='editpwsform']").serialize();
                if($('#oldpassword').val().length==0 || $('#newpassword').val().length==0 || $('#newpassword1').val().length==0 || $('#newpassword').val()!=$('#newpassword1').val()){
                    $.alert("参数不能为空");
                    return false;
                }
                $.post(Init.url.base+'?m=passport&o=index&a=ChangePassword&callback=?',pagram,function(R){
                    if(R.result=="ok"){
                        $.toast("修改成功");
                        var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                        window.location.href=window.location.href+ljf+"math="+10000*Math.random();

                    }else{
                        $.alert(R.message);
                    }
                },"json");
                return false;
            });
            //修改密码
            $("form[name='setpwsform']").submit(function(){
                var pagram = $("form[name='setpwsform']").serialize();
                $.post(Init.url.base+'?m=passport&o=index&a=ChangePassword&callback=?',pagram,function(R){
                    if(R.result=="ok"){
                        //window.location.reload();
                        $.toast("修改成功");
                        var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                        window.location.href=window.location.href+ljf+"math="+10000*Math.random();
                    }else{
                        $.alert(R.message);
                    }
                },"json");
                return false;
            });

            //解绑第三方账户
            $(".unbindAccount").on("click",function(){
                if(!confirm('你确定解除绑定吗？')){ return false;};
                var o = $(this),id= o.data("id"),type = o.data("type");
                $.post(Init.url.base+'?m=user&o=index&a=UnBindAccount&callback=?',{ id:id,type:type },function(R){
                    if(R.result=="ok"){
                        //window.location.reload();
                        var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                        window.location.href=window.location.href+ljf+"math="+10000*Math.random();

                    }else{
                        $.alert(R.message);
                    }
                },"json");
                return false
            })

        },
        countOrderDetailPrice:function(){
            var account =  parseFloat($("#account").val());
            if($("#yhm_value").length>0){
                var yhm_value = parseFloat($("#yhm_value").val());
            }else{
                var yhm_value = 0;
            }
            if($("#youhui").length>0){
                var youhui = parseFloat($("#youhui").text());
            }else{

                var youhui = 0;
            }
            if($("#coupon").length>0){
                var coupon_value = $("#coupon").find("option:selected").data("fee");
                var all_yhm_price = yhm_value + parseFloat(coupon_value);
            }else{
                var all_yhm_price = yhm_value;
            }

            var kd_price = $("#kd_price").length>0?parseFloat($("#kd_price").text()):0;
            var reward_value = $("#reward_value").length>0?parseFloat($("#reward_value").val()):0;
            account = account-parseFloat(youhui)-parseFloat(all_yhm_price)-parseFloat(reward_value);
            if(account<0){
                account = 0;
            }
            $("#true_pay_account").text(parseFloat(account+kd_price).toFixed(2));
            $("#pay_account").val(parseFloat(account+kd_price));
        },
        handleOrderDetaillProduct: function () {
            $(function(){
                //删除订单
                $(".actionDelOrder").on("click",function(){
                    if(!confirm('删除订单后无法恢复，确定删除？')){ return false;};
                    var o = $(this),id = o.data("id");
                    $.post(Init.url.base+'?m=Order&o=index&a=DeleteOrder&callback=?',{ id:id },function(R){
                        if(R.result=="ok"){
                            window.location.href= Init.url.base+"s"+Init.shop_id+"/order";
                        }else{
                            $.alert(R.message);
                        }
                    },"json");
                    return false;
                });

                $(".actionChangeExpress").on("click",function(){
                    $("#change-express-box").modal("show");
                    return false;
                });
                $(".actionChangeAccount").on("click",function(){
                    $("#change-account-box").modal("show");
                    return false;
                });


                //quzhifu
                $("form[name='orderpay']").submit(function() {
                    var param = $(this).serialize();
                    $(".actionVerifyOrder").addClass("disabled").html("提交中");
                    $.post(Init.url.base+'?m=Shop&o=index&a=saveOrder&callback=?',param,function(R){
                        if(R.result=="ok"){
                            window.location.href= R.data.redirect;
                        }else{
                            $.alert(R.message);
                        }
                        $(".actionVerifyOrder").removeClass("disabled").html("确认订单");
                    },"json");
                    return false;
                });

                //确认收货
                $(".actionVerifyExpressOrder").on("click",function(){
                    $.showLoading("正在确认中...");
                    var o = $(this),id = o.data("id");
                    $.post(Init.url.base+'?m=Order&o=index&a=VerifyExpressOrder&callback=?',{ id:id },function(R){
                        if(R.result=="ok"){
                            //window.location.reload();
                            var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                            window.location.href=window.location.href+ljf+"math="+10000*Math.random();
                        }else{
                            $.alert(R.message);
                            $.hideLoading();
                        }
                    },"json");
                    return false;
                });

                $(".actionRefund").on("click",function(){
                    if(!confirm('申请退款后，不可恢复。确定退款？')){ return false;};
                    $.showLoading("正在确认中...");
                    var o = $(this),id = o.data("id");
                    $.post(Init.url.base+'?m=Order&o=index&a=OrderRefund&callback=?',{ order_id:id },function(R){
                        if(R.result=="ok"){
                            var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                            window.location.href=window.location.href+ljf+"math="+10000*Math.random();
                        }else{
                            $.alert(R.message);
                            $.hideLoading();
                        }
                    },"json");
                    return false;
                });


                /**
                 * 提交评价
                 */
                $("form[name='saveShopPingjia']").submit(function(){
                    var o=$(this),param = o.serialize();
                    $.post(Init.url.base+'?m=shop&o=index&a=SavePingjia&callback=?',param,function(R){
                        if(R.result=="ok"){
                            //window.location.reload();
                            var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                            window.location.href=window.location.href+ljf+"math="+10000*Math.random();
                        }else{
                            $.alert(R.message);
                        }
                    },"json");
                    return false;
                });

                //修改物流信息
                $("form[name=changeOrderExpress]").submit(function(){
                    $.showLoading("正在确认中...");
                    var param = $(this).serialize();
                    $.post(Init.url.base+'?m=order&o=index&a=SaveOrderExpress&callback=?',param,function(R){
                        if(R.result=="ok"){
                            //window.location.reload();
                            var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                            window.location.href=window.location.href+ljf+"math="+10000*Math.random();
                        }else{
                            $.alert(R.message);
                            $.hideLoading();
                        }
                    },"json");
                    return false;
                });
                //修改订单价格
                $("form[name=changeOrderPrice]").submit(function(){
                    var param = $(this).serialize();
                    $.post(Init.url.base+'?m=order&o=index&a=SaveOrderPrice&callback=?',param,function(R){
                        if(R.result=="ok"){
                            //window.location.reload();
                            var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                            window.location.href=window.location.href+ljf+"math="+10000*Math.random();

                        }else{
                            $.alert(R.message);
                        }
                    },"json");
                    return false;
                });
                $(".actionChangeOrder").on("click",function(){
                    if(!confirm('确认订单已完成？')){ return false;};
                    var o = $(this),id = o.data("id"),status= o.data("status");
                    $.post(Init.url.base+'?m=Order&o=index&a=ChangeOrderStatus&callback=?',{ status:status,id:id },function(R){
                        if(R.result=="ok"){
                            var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                            window.location.href=window.location.href+ljf+"math="+10000*Math.random();
                        }else{
                            $.alert(R.message);
                        }
                    },"json");
                    return false;
                });

                //取消订单
                $(".actionCancelOrder").on("click",function(){
                    if(!confirm('删除订单后无法恢复，确定删除？若已支付金额，请自行通过支付渠道退款。')){ return false;};
                    var o = $(this),id = o.data("id"),status= o.data("status"),message="店长关闭订单";
                    $.post(Init.url.base+'?m=Order&o=index&a=ChangeOrderStatus&callback=?',{ status:status,id:id,cancel_message:message },function(R){
                        if(R.result=="ok"){
                            //window.location.reload();
                            var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                            window.location.href=window.location.href+ljf+"math="+10000*Math.random();
                        }else{
                            $.alert(R.message);
                        }
                    },"json");
                    return false;
                });
                //保存订单
                $("form[name='orderpay']").submit(function() {
                    var param = $(this).serialize();
                    $(".actionVerifyOrder").addClass("disabled").html("提交中");
                    $.post(Init.url.base+'?m=Shop&o=index&a=saveOrder&callback=?',param,function(R){
                        if(R.result=="ok"){
                            window.location.href= R.data.redirect;
                        }else{
                            $.alert(R.message);
                        }
                        $(".actionVerifyOrder").removeClass("disabled").html("确认订单");
                    },"json");
                    return false;
                });
                if($(".fixed_button").children().children().length==0){
                    $(".fixed_button").hide();
                }

                //审核订单
                $(".actionVerifyOrder").on("click",function(){
                    var o = $(this),id = o.data("id"),status= o.data("status"),btn_text= o.text();
                    o.addClass("disabled").html("提交中...");
                    $.post(Init.url.base+'?m=Order&o=index&a=ChangeOrderStatus&callback=?',{ status:status,id:id },function(R){
                        if(R.result=="ok"){
                            //window.location.reload();
                            var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                            window.location.href=window.location.href+ljf+"math="+10000*Math.random();
                        }else{
                            $.alert(R.message);
                        }
                        o.removeClass("disabled").html(btn_text);
                    },"json");
                    return false;
                });
            });
        },
        handleOrderDetailServiceAdmin:function(){
            if($("#thumbnail-fine-uploader").length>0){
                BagongApp.handleCreateUpload("thumbnail-fine-uploader","添加图片")
            }

            $(".actionShowCancelOrderBox").on("click",function(){
                $("#cancel-box").modal("show");
                return false;
            });

            $(".actionChangeCalendar").on("click",function(){
                $("#calendar-box").modal("show");
                return false;
            });

            $(".actionVerifyServiceCode").on("click",function(){
                $("#yanzheng-box").modal("show");
                return false;
            });
            $(".actionChangeAccount").on("click",function(){
                $("#change-account-box").modal("show");
                return false;
            });

            BagongApp.handleAfterUpload();
            if($("#calendar").length>0){
                var data_start = $("#calendar").data("start");
                var data_end = $("#calendar").data("end");
                $("#calendar").html("");
                new Kalendae("calendar", {
                    months:1,
                    mode:'range',
                    selected:[data_start,data_end],
                    subscribe: {
                        'change': function (date, action) {
                            var data_range = this.getSelected();
                            var data_range_arr = data_range.split(" - "),start_date = data_range_arr[0],end_date=data_range_arr[1];
                            $("#jiyangriqi").text(this.getSelected());
                            $("#date_start").val(start_date);
                            $("#date_end").val(end_date);
                            if(typeof(end_date) != "undefined"){
                                var regEx = new RegExp("\\-","gi");
                                var startdate = new Date($('#date_start').val().replace(regEx,"/"));
                                var enddate = new Date($('#date_end').val().replace(regEx,"/"));
                                var price_day = (enddate.getTime()-startdate.getTime())/86400000;
                                var date_range = parseInt(price_day);
                                $("#jiyangtianshu").text("("+price_day+"天)");
                            }
                        }
                    }
                });
            }


            //修改订单价格
            $("form[name=changeOrderPrice]").submit(function(){
                var param = $(this).serialize();
                $("#actionChangeOrderPrice").addClass("disabled").html("提交中...");
                $.post(Init.url.base+'?m=order&o=index&a=SaveOrderPrice&callback=?',param,function(R){
                    if(R.result=="ok"){
                        //window.location.reload();
                        var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                        window.location.href=window.location.href+ljf+"math="+10000*Math.random();

                    }else{
                        $.alert(R.message);
                    }
                    $("#actionChangeOrderPrice").removeClass("disabled").html("保存");
                },"json");
                return false;
            });

            //取消订单
            $(".actionCancelOrder").on("click",function(){
                var o = $(this),id = o.data("id"),status= o.data("status"),message=$("#cancel_message").val();
                $.post(Init.url.base+'?m=Order&o=index&a=ChangeOrderStatus&callback=?',{ status:status,id:id,cancel_message:message },function(R){
                    if(R.result=="ok"){
                        //window.location.reload();
                        var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                        window.location.href=window.location.href+ljf+"math="+10000*Math.random();

                    }else{
                        $.alert(R.message);
                    }
                },"json");
                return false;
            });

            //去支付
            $(".actionTopay").on("click",function(){
                var o=$(this),param = $("form[name=orderpay]").serialize();
                o.addClass("disabled").html("提交中");
                $.post(Init.url.base+'?m=Merchant&o=index&a=saveOrder&callback=?',param,function(R){
                    if(R.result=="ok"){
                        window.location.href= R.data.redirect;
                    }else{
                        $.alert(R.message);
                    }
                    o.removeClass("disabled").html("去支付");
                },"json");
                return false;
            });

            //保存订单备注信息
            $(".actionSaveBeizhu").on("click",function(){
                var id = $(this).data("id"), order_beizhu = $("textarea[name=order_beizhu]").val();
                $.post(Init.url.base+'?m=Order&o=index&a=saveOrderBeizhu&callback=?',{ order_id:id,order_beizhu:order_beizhu },function(R){
                    if(R.result=="ok"){
                        //window.location.reload();
                        var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                        window.location.href=window.location.href+ljf+"math="+10000*Math.random();

                    }else{
                        $.alert(R.message);
                    }
                },"json");
                return false;
            });

            //修改预约日期
            $("form[name='updateOrderDate']").submit(function(){
                var param = $(this).serialize();
                $.post(Init.url.base+'?m=Order&o=index&a=AjaxUpdateOrderData&callback=?',param,function(R){
                    if(R.result=="ok"){
                        //window.location.reload();
                        var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                        window.location.href=window.location.href+ljf+"math="+10000*Math.random();

                    }else{
                        $.alert(R.message);
                    }
                },"json");
                return false;
            });
            //审核订单
            $(".actionVerifyOrder").on("click",function(){
                var o = $(this),id = o.data("id"),status= o.data("status"),btn_text= o.text();
                o.addClass("disabled").html("提交中...");
                $.post(Init.url.base+'?m=Order&o=index&a=ChangeOrderStatus&callback=?',{ status:status,id:id },function(R){
                    if(R.result=="ok"){
                        //window.location.reload();
                        var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                        window.location.href = window.location.href+ljf+"math="+10000*Math.random();

                    }else{
                        $.alert(R.message);
                        o.removeClass("disabled").html(btn_text);
                    }
                },"json");
                return false;
            });

            //删除寄养图片
            $(".actionDelPic").on("click",function(){
                if(!confirm('你确定要删除该图片吗？')){ return false;};
                var o = $(this),id= o.data("id"),order_id = o.data("orderid");
                $.getJSON(Init.url.base+'?m=Order&o=index&a=DeleteOrderPic&callback=?',{ id:id,order_id:order_id },function(R){
                    if(R.result=="ok"){
                        //window.location.reload();
                        var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                        window.location.href=window.location.href+ljf+"math="+10000*Math.random();
                    }else{
                        $.alert(R.message);
                    }

                });
                return false;
            });
            //保存寄养图片
            $("form[name='savePetAlbum']").submit(function(){
                $("#savePetPic").addClass("disabled").html("提交中...");
                var param = $(this).serialize();
                //图片地址
                var uploaddomainpre = 'http://bagong.oss-cn-qingdao.aliyuncs.com/';
                var localdomainpre = 'http://i1.bagong.cn/';
                var hlgdomainpre = 'http://bagong-i1.hlg.cc/';

                var files={},i=0;
                $('#pb-photo-list li').each(function(){
                    var o = $(this),pic = o.children(".pb-photo-li-thumb").children('img');
                    var img={};
                    img.src = pic.data('src').replace(uploaddomainpre,"").replace(localdomainpre,"").replace(hlgdomainpre,"").replace(/\//g,"").replace("_100x100_1.jpg",""); //这个替换要随不同域名 不同缩略图变化
                    var title = o.children("textarea").val();
                    var ntitle = title.replace("/\n\r/gi"," ");
                    ntitle = ntitle.replace("/\r/gi"," ");
                    ntitle = ntitle.replace("/\n/gi"," ");
                    img.title = ntitle;
                    img.width = pic.data("width");
                    img.height = pic.data("height");
                    img.type = pic.data("type");
                    files[i]=img;
                    i++;
                });
                if(i<1){
                    $.alert("请上传图片后保存");
                    return false;
                }
                //var pic_data = JSON.stringify(files);
                var pic_data = JSON.stringify(files);
                var o = JSON.parse(pic_data);
                eval("var pic_data = '"+JSON.stringify(o)+"';");
                $.post(Init.url.base+'?m=Order&o=index&a=SaveOrderAlbum&callback=?',param+"&pic_data="+pic_data,function(R){
                    if(R.result=="ok"){
                        //window.location.reload();
                        var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                        window.location.href=window.location.href+ljf+"math="+10000*Math.random();
                    }else{
                        $.alert(R.message);
                        $("#savePetPic").removeClass("disabled").html(" 提 交 ");
                    }
                },"json");
                return false;
            });
            if($(".fixed_button").children().children().length==0){
                $(".fixed_button").hide();
            }
        },
        handleOrderDetailToverify:function(){
            BagongApp.handleGetLocationAddress("user_address");

            if($(".icheck_class").is(":visible")){
                $('.icheck_class').iCheck({
                    checkboxClass: 'icheckbox_square-orange',
                    radioClass: 'iradio_square-orange',
                    increaseArea: '20%'
                });
            }

            $("input[name='daodianziqu']").on('ifChecked ifUnchecked', function(){
                countPrice();
            });

            if($("#myaddress_order_toverify").length>0){
                $.getJSON(Init.url.base+'?m=shop&o=index&a=addAddress&callback=?',function(R){
                    if(R.result=="ok"){
                        $("#myaddress_order_toverify").html(R.data);

                    }
                });
            }



            $("#wanshan_submit").on("click",function(){
                if($("#wanshan_contact").val().length<=0){
                    $("#wanshan_contact").focus();
                }
                if($("#wanshan_contact_tel").val().length<=0){
                    $("#wanshan_contact_tel").focus();
                }
                var phone = $("#wanshan_contact_tel").val();
                var patrn = /^\d{3}[-| ]?\d{8}[-| ]?\d?$/;
                if (!patrn.exec(phone)) {
                    $.alert("手机号格式不正确");
                    $("#wanshan_contact_tel").focus();
                    return false;
                }
                $("input[name='contact']").val($("#wanshan_contact").val());
                $("input[name='contact_tel']").val(phone);
                $("#wanshan_ziliao").modal("hide");
            });


            function countPrice(){
                $(".product_cell").each(function(){
                    var order_num = $(this).find(".order_num").val();
                    var price = $(this).find(".product_price").text();
                    var sp =  parseInt(order_num)*parseFloat(price);
                    $(this).find(".mp_price").text(sp.toFixed(2))
                });

                var account = 0;
                $(".mp_price").each(function(){
                    account+=parseFloat($(this).text());
                });
                var kd_price = $("input[name='kuaidifee']").val();
                if($("input[name='daodianziqu']").is(":checked")){
                    kd_price = 0;
                }
                var reward_value = 0;
                if($("#reward_value").length>0){
                    reward_value = parseFloat($("#reward_value").text());
                    if(isNaN(reward_value)){
                        reward_value = 0;
                    }
                }

                $(".d_price").text(kd_price);
                var all_account = account+parseFloat(kd_price)-reward_value;
                $("#account").text(all_account.toFixed(2));
                $("input[name='account']").val(account.toFixed(2));
            }

            countPrice();

            $('.btn-number').click(function(e){
                e.preventDefault();
                var fieldName = $(this).attr('data-field');
                var type      = $(this).attr('data-type');
                var input = $(this).parent().parent().children("."+fieldName);
                //var input = $("input[name='"+fieldName+"']");
                var currentVal = parseFloat(input.val());
                if (!isNaN(currentVal)) {
                    if(type == 'minus') {
                        if(currentVal > input.attr('min')) {
                            input.val(currentVal - 1).change();
                        }

                    } else if(type == 'plus') {

                        if(currentVal < input.attr('max')) {
                            input.val(currentVal + 1).change();
                        }

                    }
                    countPrice();
                } else {
                    input.val(0);
                }
            });
            $('.input-number').focusin(function(){
                $(this).data('oldValue', $(this).val());
            });
            $('.input-number').change(function() {
                var minValue =  parseInt($(this).attr('min'));
                var maxValue =  parseInt($(this).attr('max'));
                var valueCurrent = parseInt($(this).val());

                var name = $(this).attr('name');
                if(valueCurrent >= minValue) {
                    $(".btn-number[data-type='minus'][data-field='"+name+"']").removeAttr('disabled');
                } else {
                    //alert('Sorry, the minimum value was reached');
                    $(this).val($(this).data('oldValue'));
                }
                if(valueCurrent <= maxValue) {
                    $(".btn-number[data-type='plus'][data-field='"+name+"']").removeAttr('disabled');
                } else {
                    //alert('Sorry, the maximum value was reached');
                    $(this).val($(this).data('oldValue'));
                }
            });
            $(".input-number").keydown(function (e) {
                // Allow: backspace, delete, tab, escape, enter and .
                if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
                        // Allow: Ctrl+A
                    (e.keyCode == 65 && e.ctrlKey === true) ||
                        // Allow: home, end, left, right
                    (e.keyCode >= 35 && e.keyCode <= 39)) {
                    // let it happen, don't do anything
                    return;
                }
                // Ensure that it is a number and stop the keypress
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
            });


        },
        handleGetWebLocation:function(redirect){
            if (navigator.geolocation) {
                //获取当前地理位置
                navigator.geolocation.getCurrentPosition(function (position) {
                        var lng = position.coords.longitude;
                        var lat = position.coords.latitude;
                        // 保存地理位置信息
                        $.getJSON(Init.url.base+'?m=Info&o=index&a=SaveLocation&callback=?',{ lng:lng,lat:lat },function(R){
                            if(R.result=="ok"){
                                if(redirect==''){
                                    //window.location.reload();
                                    var ljf = window.location.href.indexOf("?") != -1 ? "&" : "?";
                                    window.location.href=window.location.href+ljf+"math="+10000*Math.random();
                                }else{
                                    window.location.href=redirect;
                                }
                            }else{
                                //定位失败
                            }
                        });
                    },
                    function (error) {
                        //处理错误
                        var message = '';
                        switch (error.code) {
                            case 1:
                                message = "位置服务被拒绝。";
                                break;
                            case 2:
                                message = "暂时获取不到位置信息。";
                                break;
                            case 3:
                                message = "获取信息超时。";
                                break;
                            default:
                                message ="未知错误。";
                                break;
                        }
                        $.getJSON(Init.url.base+'?m=Info&o=index&a=SaveLocationErrorLog&callback=?',{ message:message+",uri:"+window.location.href,id:0,pet_uid:0 },function(R){});

                    });
            } else {
                $.getJSON(Init.url.base+'?m=Info&o=index&a=SaveLocationErrorLog&callback=?',{ message:"你的浏览器不支持HTML5来获取地理位置信息，uri:"+window.location.href,id:0,pet_uid:0 },function(R){});

            }
        },
        handleGetLocationAddress:function(id,allowweixinjs){
            if (navigator.geolocation) {
                //获取当前地理位置
                navigator.geolocation.getCurrentPosition(function (position) {
                        var lng = position.coords.longitude;
                        var lat = position.coords.latitude;
                        // 保存地理位置信息
                        $.getJSON(Init.url.base+'?m=Info&o=index&a=SaveLocation&with_address=1&callback=?',{ lng:lng,lat:lat },function(R){
                            if(R.result=="ok"){
                                //window.location.reload();
                                $("#"+id).val(R.data);
                            }else{
                                //定位失败
                            }
                        });
                    },
                    function (error) {
                        //处理错误
                        var message = '';
                        switch (error.code) {
                            case 1:
                                message = "位置服务被拒绝。";
                                break;
                            case 2:
                                message = "暂时获取不到位置信息。";
                                break;
                            case 3:
                                message = "获取信息超时。";
                                break;
                            default:
                                message ="未知错误。";
                                break;
                        }
                        if(allowweixinjs){
                            weixin_getlocation();
                        }
                        $.getJSON(Init.url.base+'?m=Info&o=index&a=SaveLocationErrorLog&callback=?',{ message:message },function(R){});
                    });
            }else{
                if(allowweixinjs){
                    weixin_getlocation();
                }
                $.getJSON(Init.url.base+'?m=Info&o=index&a=SaveLocationErrorLog&callback=?',{ message:"你的浏览器不支持HTML5来获取地理位置信息。" },function(R){});
            }
            $("#getLocationAddress").removeClass("disabled").html("定位");
        },
        handleGetWeixinLocation:function(id,url){
            wx.ready(function () {
                wx.getLocation({
                    success: function (res) {
                        var lng = res.longitude; // 纬度，浮点数，范围为90 ~ -90
                        var lat = res.latitude; // 经度，浮点数，范围为180 ~ -180。
                        var speed = res.speed; // 速度，以米/每秒计
                        var accuracy = res.accuracy; // 位置精度
                        // 保存地理位置信息
                        $.getJSON(Init.url.base+'?m=Info&o=index&a=SaveLocation&with_address=1&location_from=3&callback=?',{ lng:lng,lat:lat },function(R){
                            if(R.result=="ok"){
                                $("#"+id).val(R.data);
                                $("#getLocationAddress").removeClass("disabled").html("定位");
                                if(url!=""){
                                    window.location.href = url;
                                }
                            }else{
                                //定位失败
                            }
                        });
                    },
                    cancel: function (res) {
                        $.getJSON(Init.url.base+'?m=Info&o=index&a=SaveLocationErrorLog&type=weixin&with_address=1&callback=?',{ message:'用户拒绝授权获取地理位置' },function(R){
                            if(url!=""){
                                getWeblocation(url);
                            }
                        });
                    },
                    fail:function(res){
                        $.getJSON(Init.url.base+'?m=Info&o=index&a=SaveLocationErrorLog&type=weixin&with_address=1&callback=?',{ message:'获取地理位置失败'},function(R){
                            if(url!=""){
                                getWeblocation(url);
                            }
                        });
                    }
                });

            });
        },
        handleDazhuanpan:function(){
            var turnplate={
                restaraunts:[],				//大转盘奖品名称
                colors:[],					//大转盘奖品区块对应背景颜色
                outsideRadius:192,			//大转盘外圆的半径
                textRadius:155,				//大转盘奖品位置距离圆心的距离
                insideRadius:68,			//大转盘内圆的半径
                startAngle:0,				//开始角度
                bRotate:false				//false:停止;ture:旋转
            };
            function rnd(n, m){
                var random = Math.floor(Math.random()*(m-n+1)+n);
                return random;

            }
            $(function () {
                //动态添加大转盘的奖品与奖品区域背景颜色
                turnplate.restaraunts =JSON.parse(Init.restaraunts);
                turnplate.colors = ["#FFF4D6", "#FFFFFF", "#FFF4D6", "#FFFFFF","#FFF4D6", "#FFFFFF", "#FFF4D6", "#FFFFFF","#FFF4D6", "#FFFFFF"];

                var rotateTimeOut = function (){
                    $('#wheelcanvas').rotate({
                        angle:0,
                        animateTo:2160,
                        duration:8000,
                        callback:function (){
                            $.alert("网络超时，请检查您的网络设置！");
                        }
                    });
                };

                //旋转转盘 item:奖品位置; txt：提示语;
                var rotateFn = function (item, txt){
                    var angles = item * (360 / turnplate.restaraunts.length) - (360 / (turnplate.restaraunts.length*2));
                    if(angles<270){
                        angles = 270 - angles;
                    }else{
                        angles = 360 - angles + 270;
                    }
                    $('#wheelcanvas').stopRotate();
                    $('#wheelcanvas').rotate({
                        angle:0,
                        animateTo:angles+1800,
                        duration:8000,
                        callback:function (){
                            $.alert("恭喜您，中得"+txt);
                            turnplate.bRotate = !turnplate.bRotate;
                        }
                    });
                };

                $('.pointer').click(function (){
                    var status = $(this).data("status");
                    if(!status){
                        $.alert("该店铺未开启大抽奖活动！");
                        return false;
                    }
                    if(Init.uid==0){
                        $("#login-modal").modal("show");
                        return false;
                    }

                    if(turnplate.bRotate)return;
                    turnplate.bRotate = !turnplate.bRotate;
                    //获取随机数(奖品个数范围内)
                    // var item = rnd(1,turnplate.restaraunts.length);

                    $.getJSON(Init.url.base+'?m=shop&o=index&a=SaveDazhuanpanCJ&shop_id='+Init.shop_id+'&callback=?',{ },function(R) {
                        if (R.result == "ok") {
                            var item =  R.data.id;
                            rotateFn(R.data.id, turnplate.restaraunts[item-1]);
                            console.log(R.data.id);
                        }else{
                            $.alert(R.message);
                        }
                    });

                });
                drawRouletteWheel();
            });
            function drawRouletteWheel() {
                var canvas = document.getElementById("wheelcanvas");
                if (canvas.getContext) {
                    //根据奖品个数计算圆周角度
                    var arc = Math.PI / (turnplate.restaraunts.length/2);
                    var ctx = canvas.getContext("2d");
                    //在给定矩形内清空一个矩形
                    ctx.clearRect(0,0,422,422);
                    //strokeStyle 属性设置或返回用于笔触的颜色、渐变或模式
                    ctx.strokeStyle = "#FFBE04";
                    //font 属性设置或返回画布上文本内容的当前字体属性
                    ctx.font = '16px Microsoft YaHei';
                    for(var i = 0; i < turnplate.restaraunts.length; i++) {
                        var angle = turnplate.startAngle + i * arc;
                        ctx.fillStyle = turnplate.colors[i];
                        ctx.beginPath();
                        //arc(x,y,r,起始角,结束角,绘制方向) 方法创建弧/曲线（用于创建圆或部分圆）
                        ctx.arc(211, 211, turnplate.outsideRadius, angle, angle + arc, false);
                        ctx.arc(211, 211, turnplate.insideRadius, angle + arc, angle, true);
                        ctx.stroke();
                        ctx.fill();
                        //锁画布(为了保存之前的画布状态)
                        ctx.save();

                        //----绘制奖品开始----
                        ctx.fillStyle = "#E5302F";
                        var text = turnplate.restaraunts[i];
                        var line_height = 17;
                        //translate方法重新映射画布上的 (0,0) 位置
                        ctx.translate(211 + Math.cos(angle + arc / 2) * turnplate.textRadius, 211 + Math.sin(angle + arc / 2) * turnplate.textRadius);

                        //rotate方法旋转当前的绘图
                        ctx.rotate(angle + arc / 2 + Math.PI / 2);

                        /** 下面代码根据奖品类型、奖品名称长度渲染不同效果，如字体、颜色、图片效果。(具体根据实际情况改变) **/
                        var num = text.replace(/[^0-9]/ig,"");
                        if(text.indexOf(num)>=0){//数字加粗
                            var texts = text.split(num);
                            for(var j = 0; j<texts.length; j++){
                                ctx.font = j == 0?'bold 20px Microsoft YaHei':'16px Microsoft YaHei';
                                if(j == 0){
                                    ctx.fillText(texts[j]+num, -ctx.measureText(texts[j]+num).width / 2, j * line_height);
                                }else{
                                    ctx.fillText(texts[j], -ctx.measureText(texts[j]).width / 2, j * line_height);
                                }
                            }
                        }else if(text.indexOf(num) == -1 && text.length>6){//奖品名称长度超过一定范围
                            text = text.substring(0,6)+"||"+text.substring(6);
                            var texts = text.split("||");
                            for(var j = 0; j<texts.length; j++){
                                ctx.fillText(texts[j], -ctx.measureText(texts[j]).width / 2, j * line_height);
                            }
                        }else{
                            //在画布上绘制填色的文本。文本的默认颜色是黑色
                            //measureText()方法返回包含一个对象，该对象包含以像素计的指定字体宽度
                            ctx.fillText(text, -ctx.measureText(text).width / 2, 0);
                        }
                        //把当前画布返回（调整）到上一个save()状态之前
                        ctx.restore();
                        //----绘制奖品结束----
                    }
                }
            }
        },

        handleServiceBase:function(){
            $('.form-wrapper input').iCheck({
                checkboxClass: 'icheckbox_square-orange',
                radioClass: 'iradio_square-orange',
                increaseArea: '20%'
            });
            $(".actionJiamuBiao").on("click",function(){
                $("#jiamubiao_popup").popup();
            });
            $(".actionShangmenDesc").on("click",function(){
                $("#shangmen_popup").popup();
            });
            //载入的我的宠物
            if($("#MyPet").length>0){
                $.getJSON(Init.url.base+'?m=shop&o=index&a=LoadMyPet&callback=?',{ sid:Init.shop_id,type:"jiyang" },function(R){
                    if(R.result=="ok"){
                        $("#MyPet").html(R.data);
                        if(R.data.length>220){
                            $(".cell_pet").iCheck({
                                checkboxClass: 'icheckbox_square-orange',
                                radioClass: 'iradio_square-orange',
                                increaseArea: '20%'
                            }).on('ifChecked ifUnchecked', function(){
                                var i=0;
                                $(".cell_pet").each(function(){
                                    if($(this).is(':checked')){
                                        i++;
                                    }
                                });
                                if(i>0){
                                    $("#order_num").val(i);
                                    BagongApp.handleCountJiyangPriceNew();
                                    BagongApp.handleCountYiliaoPrice();
                                }
                            });

                        }else{
                            $.modal({
                                title: "添加爱宠提示",
                                text: "系统检测到您尚未添加您的爱宠",
                                buttons: [
                                    { text: "暂不添加", className: "default", onClick: function(){
                                        $("#MyPet").parent().hide();
                                        return false;
                                    } },
                                    { text: "立即添加", onClick: function(){ $(".actionAddPet").trigger("click"); } },

                                ]
                            });
                        }
                        BagongApp.handleAddPet();
                    }else{

                        if(R.message=="please login"){
                            $.modal({
                                title: "请先登录",
                                text: "系统检测到您尚未登录，预约需要先登录哦！",
                                buttons: [
                                    { text: "先看看",  className: "default", onClick: function(){

                                    } },
                                    { text: "去登录", onClick: function(){
                                          //ajax登录
                                          window.location.href = "/s"+Init.shop_id+"/user"
                                     } },
                                ]
                            });

                        }
                        $("#MyPet").html('<button type="button" class="actionAddPet btn btn-info">添加宠物</button>');
                        BagongApp.handleAddPet();

                    }
                });
            }

            //数量
            $('.btn-number').click(function(e){
                e.preventDefault();
                var fieldName = $(this).attr('data-field');
                var type  = $(this).attr('data-type');
                var input = $("input[name='"+fieldName+"']");
                var currentVal = parseInt(input.val());
                if (!isNaN(currentVal)) {
                    if(type == 'minus') {
                        if(currentVal > input.attr('min')) {
                            input.val(currentVal - 1).change();
                        }
                        if(parseInt(input.val()) == input.attr('min')) {
                            $(this).attr('disabled', true);
                        }
                    } else if(type == 'plus') {

                        if(currentVal < input.attr('max')) {
                            input.val(currentVal + 1).change();
                        }
                        if(parseInt(input.val()) == input.attr('max')) {
                            $(this).attr('disabled', true);
                        }
                    }
                } else {
                    input.val(0);
                }
            });
            $('.input-number').focusin(function(){
                $(this).data('oldValue', $(this).val());
            });
            $('.input-number').change(function() {
                var minValue =  parseInt($(this).attr('min'));
                var maxValue =  parseInt($(this).attr('max'));
                var valueCurrent = parseInt($(this).val());
                var name = $(this).attr('name');
                if(valueCurrent >= minValue) {
                    $(".btn-number[data-type='minus'][data-field='"+name+"']").removeAttr('disabled')
                } else {
                    //alert('Sorry, the minimum value was reached');
                    $(this).val($(this).data('oldValue'));
                }
                if(valueCurrent <= maxValue) {
                    $(".btn-number[data-type='plus'][data-field='"+name+"']").removeAttr('disabled')
                } else {
                    //alert('Sorry, the maximum value was reached');
                    $(this).val($(this).data('oldValue'));
                }
            });
            $(".input-number").keydown(function (e) {
                // Allow: backspace, delete, tab, escape, enter and .
                if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
                        // Allow: Ctrl+A
                    (e.keyCode == 65 && e.ctrlKey === true) ||
                        // Allow: home, end, left, right
                    (e.keyCode >= 35 && e.keyCode <= 39)) {
                    // let it happen, don't do anything
                    return;
                }
                // Ensure that it is a number and stop the keypress
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
            });

            $("input[name='shangmen']").eq(0).iCheck('check');
            //是否上门
            $("input[name='shangmen']").on("ifClicked",function(){
                var need_shangmen = $(this).val();
                if(need_shangmen==1){
                    $(".address-box").show();
                }else{
                    $(".address-box").hide();
                }
            });


            BagongApp.handleAddPet();

            if(Init.uid==0){
                $("input[name='contact_tel']").blur(function(){
                    var o = $(this), contact_tel = o.val();
                    $.getJSON(Init.url.base+'passport.php?m=Passport&o=index&a=CheckPhoneIsRegistered&callback=?',{ phone:contact_tel },function(JSON){
                        if(JSON.result=="ok"){
                            $("#logname").val(contact_tel);
                            $("#login-modal").modal('show');
                            return false;
                        }
                    })
                })
            }
        },
        handleAddPet:function(){
            $(".actionAddPet").on("click",function(){
                $.showLoading("正在加载...");
                $.getJSON(Init.url.base+'?m=shop&o=index&a=Addpet&callback=?',{ sid:Init.shop_id},function(R){
                    if(R.result=="ok"){
                        $("#addpet_box").html(R.data);
                        $("#addpet").popup();
                        //$('#addpet').modal('show');
                        //$("#addpet").on('shown.bs.modal', function (e) {
                        $.hideLoading();
                        $("form[name='savePet']").submit(function(){
                            var o=$(this),param = o.serialize();
                            var sub_btn = o.find("button[type=submit]");
                            var sub_btn_text = sub_btn.html();
                            sub_btn.addClass("disabled").html("提交中...");
                            $.showLoading("正在加载...");
                            $.post(Init.url.base+'?m=shop&o=index&a=SavePet&callback=?',param,function(R){
                                if(R.result=="ok"){
                                    //$('#addpet').modal('hide');
                                    $.closePopup()
                                    $.getJSON(Init.url.base+'?m=shop&o=index&a=LoadMyPet&callback=?',{ sid:Init.shop_id,uid:R.data },function(R){
                                        if(R.result=="ok"){
                                            $("#MyPet").html(R.data);
                                            $(".cell_pet").iCheck({
                                                checkboxClass: 'icheckbox_square-orange',
                                                radioClass: 'iradio_square-orange',
                                                increaseArea: '20%'
                                            }).on('ifChecked ifUnchecked', function(){
                                                var i=0;
                                                $(".cell_pet").each(function(){
                                                    if($(this).is(':checked')){
                                                        i++;
                                                    }
                                                });
                                                if(i>0){
                                                    $("#order_num").val(i);
                                                    BagongApp.handleCountJiyangPriceNew();
                                                    BagongApp.handleCountYiliaoPrice();
                                                }
                                            });
                                        }
                                    });
                                    sub_btn.removeClass("disabled").html(sub_btn_text);
                                }else{
                                    $.alert(R.message);
                                    sub_btn.removeClass("disabled").html(sub_btn_text);
                                }
                            },"json");
                            $.hideLoading();
                            return false;
                        });
                        //});
                    }
                });
            });
        },
        handleCountJiyangPriceNew:function(){
            console.log("handleCountJiyangPriceNew");
            //计算寄养价格
            if($("input[name='order_num']").val().length>0 && $("input[name='type']").val()=="jiyang"){
                if($("input[name='order_num']").val().length<=0){
                    $("input[name='order_num']").focus();
                    return false;
                }
                if($('#date_start').val().length>0){
                    var regEx = new RegExp("\\-","gi");
                    var startdate = new Date($('#date_start').val().replace(regEx,"/"));
                    var enddate = new Date($('#date_end').val().replace(regEx,"/"));
                    if(enddate !="Invalid Date"){
                        var price_day = (enddate.getTime()-startdate.getTime())/86400000;
                        $("#price_day").val(price_day);
                        $("#jiyangtianshu").text("("+price_day+"天)");
                    }else{
                        $("#jiyangtianshu").text("请选择截至日期");
                    }
                }
                var num = parseInt($("input[name='order_num']").val());
/*                if($("select[name='order_type']").val()=="dog"){
                    var pettype = $("select[name='dog_size']").val()+"_d";
                }else{
                    var pettype = $("select[name='order_type']").val()+"_d";
                }
                if($("#"+pettype).length>0){
                    var price1 = parseInt($("#"+pettype).text().replace("￥",""));
                }else{
                    var price1=0;
                }*/
                var item_obj = $("select[name='item_id']");
                var price1 = item_obj.find("option:checked").data("price");
                console.log("price1",price1);
                console.log("num",num);

                $("input[name='unit-price']").val(price1);
                var price2 = price1;
                if(num>0){
                    price2 = price1*num;
                }
                console.log("price2",price2);
                $("#price").val(price2);
                if(typeof(enddate) != "undefined" && enddate !="Invalid Date"){
                    $("#order_account").text(price_day*price2);
                }else{
                    $("#order_account").text(0);
                }
            }
        },
        handleCountJiyangPrice:function(){
            console.log("handleCountJiyangPrice");
            //计算寄养价格
            if($("input[name='order_num']").length>0){
                if($("input[name='order_num']").val().length<=0){
                    $("input[name='order_num']").focus();
                    return false;
                }
                if($('#date_start').val().length>0){
                    var regEx = new RegExp("\\-","gi");
                    var startdate = new Date($('#date_start').val().replace(regEx,"/"));
                    var enddate = new Date($('#date_end').val().replace(regEx,"/"));
                    if(enddate !="Invalid Date"){
                        var price_day = (enddate.getTime()-startdate.getTime())/86400000;
                        $("#price_day").val(price_day);
                        $("#jiyangtianshu").text("("+price_day+"天)");
                    }else{
                        $("#jiyangtianshu").text("请选择截至日期");
                    }
                }
                var num = parseInt($("input[name='order_num']").val());

                if($("select[name='order_type']").val()=="dog"){
                    var pettype = $("select[name='dog_size']").val()+"_d";
                }else{
                    var pettype = $("select[name='order_type']").val()+"_d";
                }
                if($("#"+pettype).length>0){
                    var price1 = parseInt($("#"+pettype).text().replace("￥",""));
                }else{
                    var price1=0;
                }
                console.log("pettype",pettype);
                console.log("price1",price1);
                console.log("num",num);

                $("input[name='unit-price']").val(price1);
                var price2 = price1;
                if(num>0){
                    price2 = price1*num;
                }
                console.log("price2",price2);
                $("#price").val(price2);
                if(typeof(enddate) != "undefined" && enddate !="Invalid Date"){
                    $("#order_account").text(price_day*price2);
                }else{
                    $("#order_account").text(0);
                }
            }
        },
        handleServiceJiyang:function(){
            BagongApp.handleServiceBase();
            if($("#calendar").length>0){
                $("#calendar").html("");
                new Kalendae("calendar", {
                    months:1,
                    mode:'range',
                    format :"YYYY-MM-DD",
                    direction:'today-future',
                    //blackout: "",不可用的日期
                    subscribe: {
                        'change': function (date, action) {
                            var data_range = this.getSelected();
                            var data_range_arr = data_range.split(" - "),start_date = data_range_arr[0],end_date=data_range_arr[1];
                            $("#select-date-range span").text(this.getSelected());
                            $("#date_start").val(start_date);
                            $("#date_end").val(end_date);
                            BagongApp.handleCountJiyangPriceNew();
                        }
                    }
                });
            }
            //选择宠物类型
            $("#order_type,#order_num,select[name='item_id']").change(function(){
                //BagongApp.handleCountJiyangPrice();
                BagongApp.handleCountJiyangPriceNew();
                BagongApp.handleCountYiliaoPrice();
            });

            //提交订单
            $("form[name='save-jiyang-order']").submit(function(){
                var o = $(this);
                if($("input[name='order_date_start']").val().length<=0)  { $.alert("寄养起始日期不能为空"); return false;}
                if($("input[name='order_date_end']").val().length<=0) { $.alert("寄养截止日期不能为空"); return false;}
                var contact_tel = o.find("input[name='contact_tel']");
                var contacts = o.find("input[name='contacts']");
                if(contacts.val().length<=0){
                    $.alert("请输入联系人姓名");
                    contacts.focus();
                    return false;
                }
                if(contact_tel.val().length<=0){
                    $.alert("请输入手机号");
                    contact_tel.focus();
                    return false;
                }
                var param = o.serialize();
                o.find("button[type=submit]").addClass("disabled").val("提交中....");
                $.post(Init.url.base+'?m=merchant&o=index&a=SaveOrder&callback=?',param,function(R){
                    if(R.result=="ok"){
                        if(typeof(R.data.redirect)!="undefined"){
                            window.location.href=R.data.redirect;
                        }else{
                            window.location.href = Init.url.base+"s"+Init.shop_id+"/order";
                        }
                    }else{
                        $.alert(R.message);
                    }
                    o.find("button[type=submit]").removeClass("disabled").val(" 提 交 订 单 ");
                },'json');
                return false;
            });
            //load tuangou
            if($("#tuangou_box").length>0){
                $.getJSON(Init.url.base+"?m=shop&o=index&a=LoadTuangou&callback=?",{ type:"jiyang",sid:Init.shop_id },function(R){
                    if(R.result=="ok"){
                        $("#tuangou_box").html(R.data);
                    }
                });
            }
        },

        handleServiceMeirong:function(){
            BagongApp.handleServiceBase();



            $(".yuyue_datetimePicker").datetimePicker({
                "min": moment().format('YYYY-MM-DD'),
                "max": moment().add(10,'months').format('YYYY-MM-DD')
            });




            $(".actionCountPrice").on("click",function(){
                var o = $(this),param = $("form[name='save-meirong-order']").serialize();
                $("#order_account").html(0);
                $.showLoading("正在计算...");
                $.post(Init.url.base+'?m=shop&o=index&a=CountMeirongPrice&callback=?',param,function(R){
                    if(R.result=="ok"){
                        $.toast("计算价格仅供参考，以实体店消费金额为准", "text");
                        $("#order_account").html(R.data);
                        $.hideLoading();
                    }else{
                        $.alert(R.message);
                        $.hideLoading();
                    }
                    o.find("button[type=submit]").removeClass("disabled").val(" 提 交 订 单 ");
                },'json');
            });

            //提交订单
            $("form[name='save-meirong-order']").submit(function(){
                var o = $(this),type = o.find("input[name=type]:checked").val();
                var param = o.serialize();
                o.find("button[type=submit]").addClass("disabled").val("提交中....");
                $.post(Init.url.base+'index.php?m=shop&o=index&a=SaveServiceOrder&callback=?',param,function(R){
                    if(R.result=="ok"){
                        window.location.href=R.data.redirect;
                    }else{
                        $.alert(R.message);
                        o.find("button[type=submit]").removeClass("disabled").val("确认");
                    }
                },'json');
                return false;
            });


            //load tuangou
            if($("#tuangou_box").length>0){
                $.getJSON(Init.url.base+"?m=shop&o=index&a=LoadTuangou&callback=?",{ type:"meirong",sid:Init.shop_id },function(R){
                    if(R.result=="ok"){
                        $("#tuangou_box").html(R.data);
                    }
                });
            }
        },

        handleServiceItem:function(){
            BagongApp.handleServiceBase();

            //提交订单
            $("form[name='save-service-order']").submit(function(){
                var o = $(this),param = o.serialize();
                o.find("button[type=submit]").addClass("disabled").val("提交中....");
                $.post(Init.url.base+'index.php?m=shop&o=index&a=SaveServiceOrder&callback=?',param,function(R){
                    if(R.result=="ok"){
                        window.location.href=R.data.redirect;
                    }else{
                        $.alert(R.message);
                    }
                    o.find("button[type=submit]").removeClass("disabled").val("确认");
                },'json');
                return false;
            });

        },
        handleCountYiliaoPrice:function(){

            var service_fee = parseFloat($("#service_type_name").find("option:selected").data("v"));
            if(!isNaN(service_fee)){
                var num = parseInt($("input[name='order_num']").val());
                var account = service_fee*num;
                $(".yiliao_order_account").text(account);
                $("#service_fee").val(account);
            }else{
                $(".yiliao_order_account").text(0);
                $("#service_fee").val(0);
            }
        },
        handleServiceYiliao:function(){
            BagongApp.handleServiceBase();

            BagongApp.handleCountYiliaoPrice();

            $('input[name="type"],input[name="order_type"]').on('ifChecked', function(){
                BagongApp.handleCountYiliaoPrice();
            });

            $("#service_type_name").change(function(){
                BagongApp.handleCountYiliaoPrice();
            });

            //提交订单
            $("form[name='save-yimiao-order']").submit(function(){
                var o = $(this),type = o.find("input[name=type]:checked").val();
                var param = o.serialize();
                o.find("button[type=submit]").addClass("disabled").val("提交中....");
                $.post(Init.url.base+'index.php?m=shop&o=index&a=SaveServiceOrder&callback=?',param,function(R){
                    if(R.result=="ok"){
                        window.location.href=R.data.redirect;
                    }else{
                        $.alert(R.message);
                    }
                    o.find("button[type=submit]").removeClass("disabled").val("确认");
                },'json');
                return false;
            });
            /*$("form[name='save-yimiao-order']").submit(function(){
                var o = $(this),type = o.find("input[name=type]:checked").val();
                var contact_tel = o.find("input[name='contact_tel']");
                var contacts = o.find("input[name='contacts']");
                if(contacts.val().length<=0){
                    $.alert("请输入联系人姓名");
                    contacts.focus();
                    return false;
                }
                if(contact_tel.val().length<=0){
                    $.alert("请输入手机号");
                    contact_tel.focus();
                    return false;
                }
                var param = o.serialize();
                o.find("button[type=submit]").addClass("disabled").val("提交中....");
                $.post(Init.url.base+'index.php?m=merchant&o=index&a=SaveOrder&callback=?',param,function(R){
                    if(R.result=="ok"){
                        if(typeof(R.data.redirect)!="undefined"){
                            window.location.href=R.data.redirect;
                        }else{
                            window.location.href = Init.url.base+"s"+Init.shop_id+"/order";
                        }
                    }else{
                        $.alert(R.message);
                    }
                    o.find("button[type=submit]").removeClass("disabled").val(" 提 交 订 单 ");
                },'json');
                return false;
            });*/

            //load tuangou
            if($("#tuangou_box").length>0){
                $.getJSON(Init.url.base+"?m=shop&o=index&a=LoadTuangou&callback=?",{ type:"yiliao",sid:Init.shop_id },function(R){
                    if(R.result=="ok"){
                        $("#tuangou_box").html(R.data);
                    }
                });
            }

            if($("#yuyue_date").is(":visible")){
                !function(a){a.fn.datepicker.dates["zh-CN"]={days:["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],daysShort:["周日","周一","周二","周三","周四","周五","周六"],daysMin:["日","一","二","三","四","五","六"],months:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],monthsShort:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],today:"今日",format:"yyyy年mm月dd日",weekStart:1,clear:"清空"}}(jQuery);
                $("#yuyue_date").datepicker({  language: "zh-CN",todayHighlight: true,format: 'yyyy-mm-dd',startDate: new Date(),autoclose: true });
            }
        }

    };
}();


